repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
shuoli84/RxSwift
RxExample/RxExample/Examples/TableView/RandomUserAPI.swift
2
2056
// // RandomUserAPI.swift // RxExample // // Created by carlos on 28/5/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift class RandomUserAPI { static let sharedAPI = RandomUserAPI() private init() {} func getExampleUserResultSet() -> Observable<[User]> { let url = NSURL(string: "http://api.randomuser.me/?results=20")! return NSURLSession.sharedSession().rx_JSON(url) >- observeSingleOn(Dependencies.sharedDependencies.backgroundWorkScheduler) >- mapOrDie { json in return castOrFail(json).flatMap { (json: [String: AnyObject]) in return self.parseJSON(json) } } >- observeSingleOn(Dependencies.sharedDependencies.mainScheduler) } private func parseJSON(json: [String: AnyObject]) -> RxResult<[User]> { let results = json["results"] as? [[String: AnyObject]] let users = results?.map { $0["user"] as? [String: AnyObject] } let error = NSError(domain: "UserAPI", code: 0, userInfo: nil) if let users = users { let searchResults: [RxResult<User>] = users.map { user in let name = user?["name"] as? [String: String] let pictures = user?["picture"] as? [String: String] if let firstName = name?["first"], let lastName = name?["last"], let imageURL = pictures?["medium"] { let returnUser = User(firstName: firstName.uppercaseFirstCharacter(), lastName: lastName.uppercaseFirstCharacter(), imageURL: imageURL) return success(returnUser) } else { return failure(error) } } let values = (searchResults.filter { $0.isSuccess }).map { $0.get() } return success(values) } return failure(error) } }
mit
ec1dfdb6105b5aeee95f5051d3abd4a4
34.465517
117
0.54572
4.872038
false
false
false
false
mightydeveloper/swift
test/Prototypes/CollectionTransformers.swift
8
38898
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// // RUN: %target-run-stdlib-swift // REQUIRES: executable_test public enum ApproximateCount { case Unknown case Precise(IntMax) case Underestimate(IntMax) case Overestimate(IntMax) } public protocol ApproximateCountableSequenceType : SequenceType { /// Complexity: amortized O(1). var approximateCount: ApproximateCount { get } } /// A collection that provides an efficient way to spilt its index ranges. public protocol SplittableCollectionType : CollectionType { // We need this protocol so that collections with only forward or bidirectional // traversals could customize their splitting behavior. // // FIXME: all collections with random access should conform to this protocol // automatically. /// Splits a given range of indicies into a set of disjoint ranges covering /// the same elements. /// /// Complexity: amortized O(1). /// /// FIXME: should that be O(log n) to cover some strange collections? /// /// FIXME: index invalidation rules? /// /// FIXME: a better name. Users will never want to call this method /// directly. /// /// FIXME: return an optional for the common case when split() can not /// subdivide the range further. func split(range: Range<Index>) -> [Range<Index>] } internal func _splitRandomAccessIndexRange<Index : RandomAccessIndexType>( range: Range<Index> ) -> [Range<Index>] { let startIndex = range.startIndex let endIndex = range.endIndex let length = startIndex.distanceTo(endIndex).toIntMax() if length < 2 { return [ range ] } let middle = startIndex.advancedBy(Index.Distance(length / 2)) return [ Range(start: startIndex, end: middle), Range(start: middle, end: endIndex) ] } /// A helper object to build a collection incrementally in an efficient way. /// /// Using a builder can be more efficient than creating an empty collection /// instance and adding elements one by one. public protocol CollectionBuilderType { typealias Collection : CollectionType typealias Element = Collection.Generator.Element init() /// Gives a hint about the expected approximate number of elements in the /// collection that is being built. mutating func sizeHint(approximateSize: Int) /// Append `element` to `self`. /// /// If a collection being built supports a user-defined order, the element is /// added at the end. /// /// Complexity: amortized O(1). mutating func append(element: Collection.Generator.Element) /// Append `elements` to `self`. /// /// If a collection being built supports a user-defined order, the element is /// added at the end. /// /// Complexity: amortized O(n), where `n` is equal to `count(elements)`. mutating func appendContentsOf< C : CollectionType where C.Generator.Element == Element >(elements: C) /// Append elements from `otherBuilder` to `self`, emptying `otherBuilder`. /// /// Equivalent to:: /// /// self.appendContentsOf(otherBuilder.takeResult()) /// /// but is more efficient. /// /// Complexity: O(1). mutating func moveContentsOf(inout otherBuilder: Self) /// Build the collection from the elements that were added to this builder. /// /// Once this function is called, the builder may not be reused and no other /// methods should be called. /// /// Complexity: O(n) or better (where `n` is the number of elements that were /// added to this builder); typically O(1). mutating func takeResult() -> Collection } public protocol BuildableCollectionType : CollectionType { typealias Builder : CollectionBuilderType } extension Array : SplittableCollectionType { public func split(range: Range<Int>) -> [Range<Int>] { return _splitRandomAccessIndexRange(range) } } public struct ArrayBuilder<T> : CollectionBuilderType { // FIXME: the compiler didn't complain when I remove public on 'Collection'. // File a bug. public typealias Collection = Array<T> public typealias Element = T internal var _resultParts = [[T]]() internal var _resultTail = [T]() public init() {} public mutating func sizeHint(approximateSize: Int) { _resultTail.reserveCapacity(approximateSize) } public mutating func append(element: T) { _resultTail.append(element) } public mutating func appendContentsOf< C : CollectionType where C.Generator.Element == T >(elements: C) { _resultTail.appendContentsOf(elements) } public mutating func moveContentsOf(inout otherBuilder: ArrayBuilder<T>) { // FIXME: do something smart with the capacity set in this builder and the // other builder. _resultParts.append(_resultTail) _resultTail = [] // FIXME: not O(1)! _resultParts.appendContentsOf(otherBuilder._resultParts) otherBuilder._resultParts = [] swap(&_resultTail, &otherBuilder._resultTail) } public mutating func takeResult() -> Collection { _resultParts.append(_resultTail) _resultTail = [] // FIXME: optimize. parallelize. return Array(_resultParts.flatten()) } } extension Array : BuildableCollectionType { public typealias Builder = ArrayBuilder<Element> } //===----------------------------------------------------------------------===// // Fork-join //===----------------------------------------------------------------------===// // As sad as it is, I think for practical performance reasons we should rewrite // the inner parts of the fork-join framework in C++. In way too many cases // than necessary Swift requires an extra allocation to pin objects in memory // for safe multithreaded access. -Dmitri import SwiftShims import SwiftPrivate import Darwin import Dispatch // FIXME: port to Linux. // XFAIL: linux // A wrapper for pthread_t with platform-independent interface. public struct _stdlib_pthread_t : Equatable, Hashable { internal let _value: pthread_t public var hashValue: Int { return _value.hashValue } } public func == (lhs: _stdlib_pthread_t, rhs: _stdlib_pthread_t) -> Bool { return lhs._value == rhs._value } public func _stdlib_pthread_self() -> _stdlib_pthread_t { return _stdlib_pthread_t(_value: pthread_self()) } struct _ForkJoinMutex { var _mutex: UnsafeMutablePointer<pthread_mutex_t> init() { _mutex = UnsafeMutablePointer.alloc(1) if pthread_mutex_init(_mutex, nil) != 0 { fatalError("pthread_mutex_init") } } func `deinit`() { if pthread_mutex_destroy(_mutex) != 0 { fatalError("pthread_mutex_init") } _mutex.destroy() _mutex.dealloc(1) } func withLock<Result>(@noescape body: () -> Result) -> Result { if pthread_mutex_lock(_mutex) != 0 { fatalError("pthread_mutex_lock") } let result = body() if pthread_mutex_unlock(_mutex) != 0 { fatalError("pthread_mutex_unlock") } return result } } struct _ForkJoinCond { var _cond: UnsafeMutablePointer<pthread_cond_t> = nil init() { _cond = UnsafeMutablePointer.alloc(1) if pthread_cond_init(_cond, nil) != 0 { fatalError("pthread_cond_init") } } func `deinit`() { if pthread_cond_destroy(_cond) != 0 { fatalError("pthread_cond_destroy") } _cond.destroy() _cond.dealloc(1) } func signal() { pthread_cond_signal(_cond) } func wait(mutex: _ForkJoinMutex) { pthread_cond_wait(_cond, mutex._mutex) } } final class _ForkJoinOneShotEvent { var _mutex: _ForkJoinMutex = _ForkJoinMutex() var _cond: _ForkJoinCond = _ForkJoinCond() var _isSet: Bool = false init() {} deinit { _cond.`deinit`() _mutex.`deinit`() } func set() { _mutex.withLock { if !_isSet { _isSet = true _cond.signal() } } } /// Establishes a happens-before relation between calls to set() and wait(). func wait() { _mutex.withLock { while !_isSet { _cond.wait(_mutex) } } } /// If the function returns true, it establishes a happens-before relation /// between calls to set() and isSet(). func isSet() -> Bool { return _mutex.withLock { return _isSet } } } final class _ForkJoinWorkDeque<T> { // FIXME: this is just a proof-of-concept; very inefficient. // Implementation note: adding elements to the head of the deque is common in // fork-join, so _deque is stored reversed (appending to an array is cheap). // FIXME: ^ that is false for submission queues though. var _deque: ContiguousArray<T> = [] var _dequeMutex: _ForkJoinMutex = _ForkJoinMutex() init() {} deinit { precondition(_deque.isEmpty) _dequeMutex.`deinit`() } var isEmpty: Bool { return _dequeMutex.withLock { return _deque.isEmpty } } func prepend(element: T) { _dequeMutex.withLock { _deque.append(element) } } func tryTakeFirst() -> T? { return _dequeMutex.withLock { let result = _deque.last if _deque.count > 0 { _deque.removeLast() } return result } } func tryTakeFirstTwo() -> (T?, T?) { return _dequeMutex.withLock { let result1 = _deque.last if _deque.count > 0 { _deque.removeLast() } let result2 = _deque.last if _deque.count > 0 { _deque.removeLast() } return (result1, result2) } } func append(element: T) { _dequeMutex.withLock { _deque.insert(element, atIndex: 0) } } func tryTakeLast() -> T? { return _dequeMutex.withLock { let result = _deque.first if _deque.count > 0 { _deque.removeAtIndex(0) } return result } } func takeAll() -> ContiguousArray<T> { return _dequeMutex.withLock { let result = _deque _deque = [] return result } } func tryReplace( value: T, makeReplacement: () -> T, isEquivalent: (T, T) -> Bool ) -> Bool { return _dequeMutex.withLock { for i in _deque.indices { if isEquivalent(_deque[i], value) { _deque[i] = makeReplacement() return true } } return false } } } final class _ForkJoinWorkerThread { internal var _tid: _stdlib_pthread_t? internal let _pool: ForkJoinPool internal let _submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase> internal let _workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase> internal init( _pool: ForkJoinPool, submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>, workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase> ) { self._tid = nil self._pool = _pool self._submissionQueue = submissionQueue self._workDeque = workDeque } internal func startAsync() { var queue: dispatch_queue_t? = nil if #available(OSX 10.10, iOS 8.0, *) { queue = dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0) } else { queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0) } dispatch_async(queue!) { self._thread() } } internal func _thread() { print("_ForkJoinWorkerThread begin") _tid = _stdlib_pthread_self() outer: while !_workDeque.isEmpty || !_submissionQueue.isEmpty { _pool._addRunningThread(self) while true { if _pool._tryStopThread() { print("_ForkJoinWorkerThread detected too many threads") _pool._removeRunningThread(self) _pool._submitTasksToRandomWorkers(_workDeque.takeAll()) _pool._submitTasksToRandomWorkers(_submissionQueue.takeAll()) print("_ForkJoinWorkerThread end") return } // Process tasks in FIFO order: first the work queue, then the // submission queue. if let task = _workDeque.tryTakeFirst() { task._run() continue } if let task = _submissionQueue.tryTakeFirst() { task._run() continue } print("_ForkJoinWorkerThread stealing tasks") if let task = _pool._stealTask() { task._run() continue } // FIXME: steal from submission queues? break } _pool._removeRunningThread(self) } assert(_workDeque.isEmpty) assert(_submissionQueue.isEmpty) _pool._totalThreads.fetchAndAdd(-1) print("_ForkJoinWorkerThread end") } internal func _forkTask(task: ForkJoinTaskBase) { // Try to inflate the pool. if !_pool._tryCreateThread({ task }) { _workDeque.prepend(task) } } internal func _waitForTask(task: ForkJoinTaskBase) { while true { if task._isComplete() { return } // If the task is in work queue of the current thread, run the task. if _workDeque.tryReplace( task, makeReplacement: { ForkJoinTask<()>() {} }, isEquivalent: { $0 === $1 }) { // We found the task. Run it in-place. task._run() return } // FIXME: also check the submission queue, maybe the task is there? // FIXME: try to find the task in other threads' queues. // FIXME: try to find tasks that were forked from this task in other // threads' queues. Help thieves by stealing those tasks back. // At this point, we can't do any work to help with running this task. // We can't start new work either (if we do, we might end up creating // more in-flight work than we can chew, and crash with out-of-memory // errors). _pool._compensateForBlockedWorkerThread() { task._blockingWait() // FIXME: do a timed wait, and retry stealing. } } } } internal protocol _FutureType { typealias Result /// Establishes a happens-before relation between completing the future and /// the call to wait(). func wait() func tryGetResult() -> Result? func tryTakeResult() -> Result? func waitAndGetResult() -> Result func waitAndTakeResult() -> Result } public class ForkJoinTaskBase { final internal var _pool: ForkJoinPool? = nil // FIXME(performance): there is no need to create heavy-weight // synchronization primitives every time. We could start with a lightweight // atomic int for the flag and inflate to a full event when needed. Unless // we really need to block in wait(), we would avoid creating an event. final internal let _completedEvent: _ForkJoinOneShotEvent = _ForkJoinOneShotEvent() final internal func _isComplete() -> Bool { return _completedEvent.isSet() } final internal func _blockingWait() { _completedEvent.wait() } internal func _run() { fatalError("implement") } final public func fork() { precondition(_pool == nil) if let thread = ForkJoinPool._getCurrentThread() { thread._forkTask(self) } else { // FIXME: decide if we want to allow this. precondition(false) ForkJoinPool.commonPool.forkTask(self) } } final public func wait() { if let thread = ForkJoinPool._getCurrentThread() { thread._waitForTask(self) } else { _blockingWait() } } } final public class ForkJoinTask<Result> : ForkJoinTaskBase, _FutureType { internal let _task: () -> Result internal var _result: Result? = nil public init(_task: () -> Result) { self._task = _task } override internal func _run() { _complete(_task()) } /// It is not allowed to call _complete() in a racy way. Only one thread /// should ever call _complete(). internal func _complete(result: Result) { precondition(!_completedEvent.isSet()) _result = result _completedEvent.set() } public func tryGetResult() -> Result? { if _completedEvent.isSet() { return _result } return nil } public func tryTakeResult() -> Result? { if _completedEvent.isSet() { let result = _result _result = nil return result } return nil } public func waitAndGetResult() -> Result { wait() return tryGetResult()! } public func waitAndTakeResult() -> Result { wait() return tryTakeResult()! } } final public class ForkJoinPool { internal static var _threadRegistry: [_stdlib_pthread_t : _ForkJoinWorkerThread] = [:] internal static var _threadRegistryMutex: _ForkJoinMutex = _ForkJoinMutex() internal static func _getCurrentThread() -> _ForkJoinWorkerThread? { return _threadRegistryMutex.withLock { return _threadRegistry[_stdlib_pthread_self()] } } internal let _maxThreads: Int /// Total number of threads: number of running threads plus the number of /// threads that are preparing to start). internal let _totalThreads: _stdlib_AtomicInt = _stdlib_AtomicInt(0) internal var _runningThreads: [_ForkJoinWorkerThread] = [] internal var _runningThreadsMutex: _ForkJoinMutex = _ForkJoinMutex() internal var _submissionQueues: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = [] internal var _submissionQueuesMutex: _ForkJoinMutex = _ForkJoinMutex() internal var _workDeques: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = [] internal var _workDequesMutex: _ForkJoinMutex = _ForkJoinMutex() internal init(_commonPool: ()) { self._maxThreads = _stdlib_getHardwareConcurrency() } deinit { _runningThreadsMutex.`deinit`() _submissionQueuesMutex.`deinit`() _workDequesMutex.`deinit`() } internal func _addRunningThread(thread: _ForkJoinWorkerThread) { ForkJoinPool._threadRegistryMutex.withLock { _runningThreadsMutex.withLock { _submissionQueuesMutex.withLock { _workDequesMutex.withLock { ForkJoinPool._threadRegistry[thread._tid!] = thread _runningThreads.append(thread) _submissionQueues.append(thread._submissionQueue) _workDeques.append(thread._workDeque) } } } } } internal func _removeRunningThread(thread: _ForkJoinWorkerThread) { ForkJoinPool._threadRegistryMutex.withLock { _runningThreadsMutex.withLock { _submissionQueuesMutex.withLock { _workDequesMutex.withLock { let i = _runningThreads.indexOf { $0 === thread }! ForkJoinPool._threadRegistry[thread._tid!] = nil _runningThreads.removeAtIndex(i) _submissionQueues.removeAtIndex(i) _workDeques.removeAtIndex(i) } } } } } internal func _compensateForBlockedWorkerThread(blockingBody: () -> ()) { // FIXME: limit the number of compensating threads. let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>() let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>() let thread = _ForkJoinWorkerThread( _pool: self, submissionQueue: submissionQueue, workDeque: workDeque) thread.startAsync() blockingBody() _totalThreads.fetchAndAdd(1) } internal func _tryCreateThread( @noescape makeTask: () -> ForkJoinTaskBase? ) -> Bool { var success = false var oldNumThreads = _totalThreads.load() repeat { if oldNumThreads >= _maxThreads { return false } success = _totalThreads.compareExchange( expected: &oldNumThreads, desired: oldNumThreads + 1) } while !success if let task = makeTask() { let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>() let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>() workDeque.prepend(task) let thread = _ForkJoinWorkerThread( _pool: self, submissionQueue: submissionQueue, workDeque: workDeque) thread.startAsync() } else { _totalThreads.fetchAndAdd(-1) } return true } internal func _stealTask() -> ForkJoinTaskBase? { return _workDequesMutex.withLock { let randomOffset = pickRandom(_workDeques.indices) let count = _workDeques.count for i in _workDeques.indices { let index = (i + randomOffset) % count if let task = _workDeques[index].tryTakeLast() { return task } } return nil } } /// Check if the pool has grown too large because of compensating /// threads. internal func _tryStopThread() -> Bool { var success = false var oldNumThreads = _totalThreads.load() repeat { // FIXME: magic number 2. if oldNumThreads <= _maxThreads + 2 { return false } success = _totalThreads.compareExchange( expected: &oldNumThreads, desired: oldNumThreads - 1) } while !success return true } internal func _submitTasksToRandomWorkers< C : CollectionType where C.Generator.Element == ForkJoinTaskBase >(tasks: C) { if tasks.isEmpty { return } _submissionQueuesMutex.withLock { precondition(!_submissionQueues.isEmpty) for task in tasks { pickRandom(_submissionQueues).append(task) } } } public func forkTask(task: ForkJoinTaskBase) { while true { // Try to inflate the pool first. if _tryCreateThread({ task }) { return } // Looks like we can't create more threads. Submit the task to // a random thread. let done = _submissionQueuesMutex.withLock { () -> Bool in if !_submissionQueues.isEmpty { pickRandom(_submissionQueues).append(task) return true } return false } if done { return } } } // FIXME: return a Future instead? public func forkTask<Result>(task: () -> Result) -> ForkJoinTask<Result> { let forkJoinTask = ForkJoinTask(_task: task) forkTask(forkJoinTask) return forkJoinTask } public static var commonPool = ForkJoinPool(_commonPool: ()) public static func invokeAll(tasks: ForkJoinTaskBase...) { ForkJoinPool.invokeAll(tasks) } public static func invokeAll(tasks: [ForkJoinTaskBase]) { if tasks.isEmpty { return } if ForkJoinPool._getCurrentThread() != nil { // Run the first task in this thread, fork the rest. let first = tasks.first for t in tasks.dropFirst() { // FIXME: optimize forking in bulk. t.fork() } first!._run() } else { // FIXME: decide if we want to allow this. precondition(false) } } } //===----------------------------------------------------------------------===// // Collection transformation DSL: implementation //===----------------------------------------------------------------------===// internal protocol _CollectionTransformerStepType /*: class*/ { typealias PipelineInputElement typealias OutputElement func transform< InputCollection : CollectionType, Collector : _ElementCollectorType where InputCollection.Generator.Element == PipelineInputElement, Collector.Element == OutputElement >( c: InputCollection, _ range: Range<InputCollection.Index>, inout _ collector: Collector ) } internal class _CollectionTransformerStep<PipelineInputElement_, OutputElement_> : _CollectionTransformerStepType { typealias PipelineInputElement = PipelineInputElement_ typealias OutputElement = OutputElement_ func map<U>(transform: (OutputElement) -> U) -> _CollectionTransformerStep<PipelineInputElement, U> { fatalError("abstract method") } func filter(predicate: (OutputElement) -> Bool) -> _CollectionTransformerStep<PipelineInputElement, OutputElement> { fatalError("abstract method") } func reduce<U>(initial: U, _ combine: (U, OutputElement) -> U) -> _CollectionTransformerFinalizer<PipelineInputElement, U> { fatalError("abstract method") } func collectTo< C : BuildableCollectionType where C.Builder.Collection == C, C.Builder.Element == C.Generator.Element, C.Generator.Element == OutputElement >(_: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> { fatalError("abstract method") } func transform< InputCollection : CollectionType, Collector : _ElementCollectorType where InputCollection.Generator.Element == PipelineInputElement, Collector.Element == OutputElement >( c: InputCollection, _ range: Range<InputCollection.Index>, inout _ collector: Collector ) { fatalError("abstract method") } } final internal class _CollectionTransformerStepCollectionSource< PipelineInputElement > : _CollectionTransformerStep<PipelineInputElement, PipelineInputElement> { typealias InputElement = PipelineInputElement override func map<U>(transform: (InputElement) -> U) -> _CollectionTransformerStep<PipelineInputElement, U> { return _CollectionTransformerStepOneToMaybeOne(self) { transform($0) } } override func filter(predicate: (InputElement) -> Bool) -> _CollectionTransformerStep<PipelineInputElement, InputElement> { return _CollectionTransformerStepOneToMaybeOne(self) { predicate($0) ? $0 : nil } } override func reduce<U>(initial: U, _ combine: (U, InputElement) -> U) -> _CollectionTransformerFinalizer<PipelineInputElement, U> { return _CollectionTransformerFinalizerReduce(self, initial, combine) } override func collectTo< C : BuildableCollectionType where C.Builder.Collection == C, C.Builder.Element == C.Generator.Element, C.Generator.Element == OutputElement >(c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> { return _CollectionTransformerFinalizerCollectTo(self, c) } override func transform< InputCollection : CollectionType, Collector : _ElementCollectorType where InputCollection.Generator.Element == PipelineInputElement, Collector.Element == OutputElement >( c: InputCollection, _ range: Range<InputCollection.Index>, inout _ collector: Collector ) { for i in range { let e = c[i] collector.append(e) } } } final internal class _CollectionTransformerStepOneToMaybeOne< PipelineInputElement, OutputElement, InputStep : _CollectionTransformerStepType where InputStep.PipelineInputElement == PipelineInputElement > : _CollectionTransformerStep<PipelineInputElement, OutputElement> { typealias _Self = _CollectionTransformerStepOneToMaybeOne typealias InputElement = InputStep.OutputElement let _input: InputStep let _transform: (InputElement) -> OutputElement? init(_ input: InputStep, _ transform: (InputElement) -> OutputElement?) { self._input = input self._transform = transform super.init() } override func map<U>(transform: (OutputElement) -> U) -> _CollectionTransformerStep<PipelineInputElement, U> { // Let the closure below capture only one variable, not the whole `self`. let localTransform = _transform return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, U, InputStep>(_input) { (input: InputElement) -> U? in if let e = localTransform(input) { return transform(e) } return nil } } override func filter(predicate: (OutputElement) -> Bool) -> _CollectionTransformerStep<PipelineInputElement, OutputElement> { // Let the closure below capture only one variable, not the whole `self`. let localTransform = _transform return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, OutputElement, InputStep>(_input) { (input: InputElement) -> OutputElement? in if let e = localTransform(input) { return predicate(e) ? e : nil } return nil } } override func reduce<U>(initial: U, _ combine: (U, OutputElement) -> U) -> _CollectionTransformerFinalizer<PipelineInputElement, U> { return _CollectionTransformerFinalizerReduce(self, initial, combine) } override func collectTo< C : BuildableCollectionType where C.Builder.Collection == C, C.Builder.Element == C.Generator.Element, C.Generator.Element == OutputElement >(c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C> { return _CollectionTransformerFinalizerCollectTo(self, c) } override func transform< InputCollection : CollectionType, Collector : _ElementCollectorType where InputCollection.Generator.Element == PipelineInputElement, Collector.Element == OutputElement >( c: InputCollection, _ range: Range<InputCollection.Index>, inout _ collector: Collector ) { var collectorWrapper = _ElementCollectorOneToMaybeOne(collector, _transform) _input.transform(c, range, &collectorWrapper) collector = collectorWrapper._baseCollector } } struct _ElementCollectorOneToMaybeOne< BaseCollector : _ElementCollectorType, Element_ > : _ElementCollectorType { typealias Element = Element_ var _baseCollector: BaseCollector var _transform: (Element) -> BaseCollector.Element? init( _ baseCollector: BaseCollector, _ transform: (Element) -> BaseCollector.Element? ) { self._baseCollector = baseCollector self._transform = transform } mutating func sizeHint(approximateSize: Int) {} mutating func append(element: Element) { if let e = _transform(element) { _baseCollector.append(e) } } mutating func appendContentsOf< C : CollectionType where C.Generator.Element == Element >(elements: C) { for e in elements { append(e) } } } protocol _ElementCollectorType { typealias Element mutating func sizeHint(approximateSize: Int) mutating func append(element: Element) mutating func appendContentsOf< C : CollectionType where C.Generator.Element == Element >(elements: C) } class _CollectionTransformerFinalizer<PipelineInputElement, Result> { func transform< InputCollection : CollectionType where InputCollection.Generator.Element == PipelineInputElement >(c: InputCollection) -> Result { fatalError("implement") } } final class _CollectionTransformerFinalizerReduce< PipelineInputElement, U, InputElementTy, InputStep : _CollectionTransformerStepType where InputStep.OutputElement == InputElementTy, InputStep.PipelineInputElement == PipelineInputElement > : _CollectionTransformerFinalizer<PipelineInputElement, U> { var _input: InputStep var _initial: U var _combine: (U, InputElementTy) -> U init(_ input: InputStep, _ initial: U, _ combine: (U, InputElementTy) -> U) { self._input = input self._initial = initial self._combine = combine } override func transform< InputCollection : CollectionType where InputCollection.Generator.Element == PipelineInputElement >(c: InputCollection) -> U { var collector = _ElementCollectorReduce(_initial, _combine) _input.transform(c, c.indices, &collector) return collector.takeResult() } } struct _ElementCollectorReduce<Element_, Result> : _ElementCollectorType { typealias Element = Element_ var _current: Result var _combine: (Result, Element) -> Result init(_ initial: Result, _ combine: (Result, Element) -> Result) { self._current = initial self._combine = combine } mutating func sizeHint(approximateSize: Int) {} mutating func append(element: Element) { _current = _combine(_current, element) } mutating func appendContentsOf< C : CollectionType where C.Generator.Element == Element >(elements: C) { for e in elements { append(e) } } mutating func takeResult() -> Result { return _current } } final class _CollectionTransformerFinalizerCollectTo< PipelineInputElement, U : BuildableCollectionType, InputElementTy, InputStep : _CollectionTransformerStepType where InputStep.OutputElement == InputElementTy, InputStep.PipelineInputElement == PipelineInputElement, U.Builder.Collection == U, U.Builder.Element == U.Generator.Element, U.Generator.Element == InputStep.OutputElement > : _CollectionTransformerFinalizer<PipelineInputElement, U> { var _input: InputStep init(_ input: InputStep, _: U.Type) { self._input = input } override func transform< InputCollection : CollectionType where InputCollection.Generator.Element == PipelineInputElement >(c: InputCollection) -> U { var collector = _ElementCollectorCollectTo<U>() _input.transform(c, c.indices, &collector) return collector.takeResult() } } struct _ElementCollectorCollectTo< Collection : BuildableCollectionType where Collection.Builder.Collection == Collection, Collection.Builder.Element == Collection.Generator.Element > : _ElementCollectorType { typealias Element = Collection.Generator.Element var _builder: Collection.Builder init() { self._builder = Collection.Builder() } mutating func sizeHint(approximateSize: Int) { _builder.sizeHint(approximateSize) } mutating func append(element: Element) { _builder.append(element) } mutating func appendContentsOf< C : CollectionType where C.Generator.Element == Element >(elements: C) { _builder.appendContentsOf(elements) } mutating func takeResult() -> Collection { return _builder.takeResult() } } internal func _optimizeCollectionTransformer<PipelineInputElement, Result>( transformer: _CollectionTransformerFinalizer<PipelineInputElement, Result> ) -> _CollectionTransformerFinalizer<PipelineInputElement, Result> { return transformer } internal func _runCollectionTransformer< InputCollection : CollectionType, Result >( c: InputCollection, _ transformer: _CollectionTransformerFinalizer<InputCollection.Generator.Element, Result> ) -> Result { dump(transformer) let optimized = _optimizeCollectionTransformer(transformer) dump(optimized) return transformer.transform(c) } //===----------------------------------------------------------------------===// // Collection transformation DSL: public interface //===----------------------------------------------------------------------===// public struct CollectionTransformerPipeline< InputCollection : CollectionType, T > { internal var _input: InputCollection internal var _step: _CollectionTransformerStep<InputCollection.Generator.Element, T> public func map<U>(transform: (T) -> U) -> CollectionTransformerPipeline<InputCollection, U> { return CollectionTransformerPipeline<InputCollection, U>( _input: _input, _step: _step.map(transform) ) } public func filter(predicate: (T) -> Bool) -> CollectionTransformerPipeline<InputCollection, T> { return CollectionTransformerPipeline<InputCollection, T>( _input: _input, _step: _step.filter(predicate) ) } public func reduce<U>(initial: U, _ combine: (U, T) -> U) -> U { return _runCollectionTransformer(_input, _step.reduce(initial, combine)) } public func collectTo< C : BuildableCollectionType where C.Builder.Collection == C, C.Generator.Element == T, C.Builder.Element == T >(c: C.Type) -> C { return _runCollectionTransformer(_input, _step.collectTo(c)) } public func toArray() -> [T] { return collectTo(Array<T>.self) } } public func transform<C : CollectionType>(c: C) -> CollectionTransformerPipeline<C, C.Generator.Element> { return CollectionTransformerPipeline<C, C.Generator.Element>( _input: c, _step: _CollectionTransformerStepCollectionSource<C.Generator.Element>()) } //===----------------------------------------------------------------------===// // Collection transformation DSL: tests //===----------------------------------------------------------------------===// import StdlibUnittest var t = TestSuite("t") t.test("fusion/map+reduce") { let xs = [ 1, 2, 3 ] let result = transform(xs) .map { $0 * 2 } .reduce(0, { $0 + $1 }) expectEqual(12, result) } t.test("fusion/map+filter+reduce") { let xs = [ 1, 2, 3 ] let result = transform(xs) .map { $0 * 2 } .filter { $0 != 0 } .reduce(0, { $0 + $1 }) expectEqual(12, result) } t.test("fusion/map+collectTo") { let xs = [ 1, 2, 3 ] let result = transform(xs) .map { $0 * 2 } .collectTo(Array<Int>.self) expectEqual([ 2, 4, 6 ], result) } t.test("fusion/map+toArray") { let xs = [ 1, 2, 3 ] let result = transform(xs) .map { $0 * 2 } .toArray() expectEqual([ 2, 4, 6 ], result) } t.test("ForkJoinPool.forkTask") { var tasks: [ForkJoinTask<()>] = [] for i in 0..<100 { tasks.append(ForkJoinPool.commonPool.forkTask { () -> () in var result = 1 for i in 0..<10000 { result = result &* i _blackHole(result) } return () }) } for t in tasks { t.wait() } } func fib(n: Int) -> Int { if n == 1 || n == 2 { return 1 } if n == 38 { print("\(pthread_self()) fib(\(n))") } if n < 39 { let r = fib(n - 1) + fib(n - 2) _blackHole(r) return r } print("fib(\(n))") let t1 = ForkJoinTask() { fib(n - 1) } let t2 = ForkJoinTask() { fib(n - 2) } ForkJoinPool.invokeAll(t1, t2) return t2.waitAndGetResult() + t1.waitAndGetResult() } t.test("ForkJoinPool.forkTask/Fibonacci") { let t = ForkJoinPool.commonPool.forkTask { fib(40) } expectEqual(102334155, t.waitAndGetResult()) } func _parallelMap(input: [Int], transform: (Int) -> Int, range: Range<Int>) -> Array<Int>.Builder { var builder = Array<Int>.Builder() if range.count < 1_000 { builder.appendContentsOf(input[range].map(transform)) } else { let tasks = input.split(range).map { (subRange) in ForkJoinTask<Array<Int>.Builder> { _parallelMap(input, transform: transform, range: subRange) } } ForkJoinPool.invokeAll(tasks) for t in tasks { var otherBuilder = t.waitAndGetResult() builder.moveContentsOf(&otherBuilder) } } return builder } func parallelMap(input: [Int], transform: (Int) -> Int) -> [Int] { let t = ForkJoinPool.commonPool.forkTask { _parallelMap(input, transform: transform, range: input.indices) } var builder = t.waitAndGetResult() return builder.takeResult() } t.test("ForkJoinPool.forkTask/MapArray") { expectEqual( Array(2..<1_001), parallelMap(Array(1..<1_000)) { $0 + 1 } ) } /* * FIXME: reduce compiler crasher t.test("ForkJoinPool.forkTask") { func fib(n: Int) -> Int { if n == 0 || n == 1 { return 1 } let t1 = ForkJoinPool.commonPool.forkTask { fib(n - 1) } let t2 = ForkJoinPool.commonPool.forkTask { fib(n - 2) } return t2.waitAndGetResult() + t1.waitAndGetResult() } expectEqual(0, fib(10)) } */ /* Useful links: http://habrahabr.ru/post/255659/ */ runAllTests()
apache-2.0
7375d72ab76a6886421fbe37b24f7e14
25.86326
108
0.653427
4.515672
false
false
false
false
apple/swift
benchmark/single-source/SetTests.swift
10
39313
//===--- SetTests.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils let size = 400 let half = size / 2 let quarter = size / 4 // Construction of empty sets. let setE: Set<Int> = [] let setOE: Set<Box<Int>> = [] // Construction kit for sets with 25% overlap let setAB = Set(0 ..< size) // 0 ..< 400 let setCD = Set(size ..< 2 * size) // 400 ..< 800 let setBC = Set(size - quarter ..< 2 * size - quarter) // 300 ..< 700 let setB = Set(size - quarter ..< size) // 300 ..< 400 let setCDS = Set(size ..< (size + (size/4))) // 400 ..< 500 let setOAB = Set(setAB.map(Box.init)) let setOCD = Set(setCD.map(Box.init)) let setOBC = Set(setBC.map(Box.init)) let setOB = Set(setB.map(Box.init)) let setOCDS = Set(setCDS.map(Box.init)) let countA = size - quarter // 300 let countB = quarter // 100 let countC = countA // 300 let countD = countB // 100 let countAB = size // 400 let countAC = countA + countC // 600 let countABC = countA + countB + countC // 700 let countABCD = countA + countB + countC + countD // 800 // Construction kit for sets with 50% overlap let setXY = Set(0 ..< size) // 0 ..< 400 let setYZ = Set(half ..< size + half) // 200 ..< 600 let setY = Set(half ..< size) // 200 ..< 400 // Two sets with 100% overlap, but different bucket counts (let's not make it // too easy...) let setP = Set(0 ..< size) let setQ: Set<Int> = { var set = Set(0 ..< size) set.reserveCapacity(2 * size) return set }() // Construction of empty array. let arrayE: Array<Int> = [] let arrayOE: Array<Box<Int>> = [] // Construction kit for arrays with 25% overlap let arrayAB = Array(0 ..< size) // 0 ..< 400 let arrayCD = Array(size ..< 2 * size) // 400 ..< 800 let arrayBC = Array(size - quarter ..< 2 * size - quarter) // 300 ..< 700 let arrayB = Array(size - quarter ..< size) // 300 ..< 400 let arrayOAB = arrayAB.map(Box.init) let arrayOCD = arrayCD.map(Box.init) let arrayOBC = arrayBC.map(Box.init) let arrayOB = arrayB.map(Box.init) // Construction kit for arrays with 50% overlap let arrayXY = Array(0 ..< size) // 0 ..< 400 let arrayYZ = Array(half ..< size + half) // 200 ..< 600 let arrayY = Array(half ..< size) // 200 ..< 400 let arrayP = Array(0 ..< size) // Construction of flexible sets. var set: Set<Int> = [] var setBox: Set<Box<Int>> = [] func set(_ size: Int) { set = Set(0 ..< size) } func setBox(_ size: Int) { setBox = Set(Set(0 ..< size).map(Box.init)) } public let benchmarks = [ // Mnemonic: number after name is percentage of common elements in input sets. BenchmarkInfo( name: "Set.isSubset.Empty.Int", runFunction: { n in run_SetIsSubsetInt(setE, setAB, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setE, setAB]) }), BenchmarkInfo( name: "Set.isSubset.Int.Empty", runFunction: { n in run_SetIsSubsetInt(setAB, setE, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setE]) }), BenchmarkInfo( name: "SetIsSubsetInt0", runFunction: { n in run_SetIsSubsetInt(setAB, setCD, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }), BenchmarkInfo( name: "SetIsSubsetBox0", runFunction: { n in run_SetIsSubsetBox(setOAB, setOCD, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }), BenchmarkInfo( name: "SetIsSubsetInt25", runFunction: { n in run_SetIsSubsetInt(setB, setAB, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setB, setAB]) }), BenchmarkInfo( name: "SetIsSubsetBox25", runFunction: { n in run_SetIsSubsetBox(setOB, setOAB, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOB, setOAB]) }), BenchmarkInfo( name: "SetIsSubsetInt50", runFunction: { n in run_SetIsSubsetInt(setY, setXY, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setY, setXY]) }), BenchmarkInfo( name: "SetIsSubsetInt100", runFunction: { n in run_SetIsSubsetInt(setP, setQ, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, setQ]) }), BenchmarkInfo( name: "Set.isSubset.Seq.Empty.Int", runFunction: { n in run_SetIsSubsetSeqInt(setE, arrayAB, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setE, arrayAB]) }), BenchmarkInfo( name: "Set.isSubset.Seq.Int.Empty", runFunction: { n in run_SetIsSubsetSeqInt(setAB, arrayE, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayE]) }), BenchmarkInfo( name: "Set.isSubset.Seq.Int0", runFunction: { n in run_SetIsSubsetSeqInt(setAB, arrayCD, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayCD]) }), BenchmarkInfo( name: "Set.isSubset.Seq.Box0", runFunction: { n in run_SetIsSubsetSeqBox(setOAB, arrayOCD, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOCD]) }), BenchmarkInfo( name: "Set.isSubset.Seq.Int25", runFunction: { n in run_SetIsSubsetSeqInt(setB, arrayBC, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setB, arrayBC]) }), BenchmarkInfo( name: "Set.isSubset.Seq.Box25", runFunction: { n in run_SetIsSubsetSeqBox(setOB, arrayOBC, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOB, arrayOBC]) }), BenchmarkInfo( name: "Set.isSubset.Seq.Int50", runFunction: { n in run_SetIsSubsetSeqInt(setY, arrayYZ, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setY, arrayYZ]) }), BenchmarkInfo( name: "Set.isSubset.Seq.Int100", runFunction: { n in run_SetIsSubsetSeqInt(setP, arrayP, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, arrayP]) }), BenchmarkInfo( name: "Set.isStrictSubset.Empty.Int", runFunction: { n in run_SetIsStrictSubsetInt(setE, setAB, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setE, setAB]) }), BenchmarkInfo( name: "Set.isStrictSubset.Int.Empty", runFunction: { n in run_SetIsStrictSubsetInt(setAB, setE, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setE]) }), BenchmarkInfo( name: "Set.isStrictSubset.Int0", runFunction: { n in run_SetIsStrictSubsetInt(setAB, setCD, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }), BenchmarkInfo( name: "Set.isStrictSubset.Box0", runFunction: { n in run_SetIsStrictSubsetBox(setOAB, setOCD, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }), BenchmarkInfo( name: "Set.isStrictSubset.Int25", runFunction: { n in run_SetIsStrictSubsetInt(setB, setAB, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setB, setAB]) }), BenchmarkInfo( name: "Set.isStrictSubset.Box25", runFunction: { n in run_SetIsStrictSubsetBox(setOB, setOAB, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOB, setOAB]) }), BenchmarkInfo( name: "Set.isStrictSubset.Int50", runFunction: { n in run_SetIsStrictSubsetInt(setY, setXY, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setY, setXY]) }), BenchmarkInfo( name: "Set.isStrictSubset.Int100", runFunction: { n in run_SetIsStrictSubsetInt(setP, setQ, false, 5000 * n) }, tags: [.validation, .api, .Set, .skip], setUpFunction: { blackHole([setP, setQ]) }), BenchmarkInfo( name: "Set.isStrictSubset.Seq.Empty.Int", runFunction: { n in run_SetIsStrictSubsetSeqInt(setE, arrayAB, true, 5000 * n) }, tags: [.validation, .api, .Set, .skip], setUpFunction: { blackHole([setE, arrayAB]) }), BenchmarkInfo( name: "Set.isStrictSubset.Seq.Int.Empty", runFunction: { n in run_SetIsStrictSubsetSeqInt(setAB, arrayE, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayE]) }), BenchmarkInfo( name: "Set.isStrictSubset.Seq.Int0", runFunction: { n in run_SetIsStrictSubsetSeqInt(setAB, arrayCD, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayCD]) }), BenchmarkInfo( name: "Set.isStrictSubset.Seq.Box0", runFunction: { n in run_SetIsStrictSubsetSeqBox(setOAB, arrayOCD, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOCD]) }), BenchmarkInfo( name: "Set.isStrictSubset.Seq.Int25", runFunction: { n in run_SetIsStrictSubsetSeqInt(setB, arrayBC, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setB, arrayBC]) }), BenchmarkInfo( name: "Set.isStrictSubset.Seq.Box25", runFunction: { n in run_SetIsStrictSubsetSeqBox(setOB, arrayOBC, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOB, arrayOBC]) }), BenchmarkInfo( name: "Set.isStrictSubset.Seq.Int50", runFunction: { n in run_SetIsStrictSubsetSeqInt(setY, arrayYZ, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setY, arrayYZ]) }), BenchmarkInfo( name: "Set.isStrictSubset.Seq.Int100", runFunction: { n in run_SetIsStrictSubsetSeqInt(setP, arrayP, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, arrayP]) }), BenchmarkInfo( name: "Set.isSuperset.Seq.Empty.Int", runFunction: { n in run_SetIsSupersetSeqInt(setAB, arrayE, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayE]) }), BenchmarkInfo( name: "Set.isSuperset.Seq.Int.Empty", runFunction: { n in run_SetIsSupersetSeqInt(setE, arrayAB, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setE, arrayAB]) }), BenchmarkInfo( name: "Set.isSuperset.Seq.Int0", runFunction: { n in run_SetIsSupersetSeqInt(setCD, arrayAB, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setCD, arrayAB]) }), BenchmarkInfo( name: "Set.isSuperset.Seq.Box0", runFunction: { n in run_SetIsSupersetSeqBox(setOCD, arrayOAB, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOCD, arrayOAB]) }), BenchmarkInfo( name: "Set.isSuperset.Seq.Int25", runFunction: { n in run_SetIsSupersetSeqInt(setB, arrayBC, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setB, arrayBC]) }), BenchmarkInfo( name: "Set.isSuperset.Seq.Box25", runFunction: { n in run_SetIsSupersetSeqBox(setOB, arrayOBC, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOB, arrayOBC]) }), BenchmarkInfo( name: "Set.isSuperset.Seq.Int50", runFunction: { n in run_SetIsSupersetSeqInt(setY, arrayYZ, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setY, arrayYZ]) }), BenchmarkInfo( name: "Set.isSuperset.Seq.Int100", runFunction: { n in run_SetIsSupersetSeqInt(setP, arrayP, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, arrayP]) }), BenchmarkInfo( name: "Set.isStrictSuperset.Seq.Empty.Int", runFunction: { n in run_SetIsStrictSupersetSeqInt(setAB, arrayE, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayE]) }), BenchmarkInfo( name: "Set.isStrictSuperset.Seq.Int.Empty", runFunction: { n in run_SetIsStrictSupersetSeqInt(setE, arrayAB, false, 5000 * n) }, tags: [.validation, .api, .Set, .skip], setUpFunction: { blackHole([setE, arrayAB]) }), BenchmarkInfo( name: "Set.isStrictSuperset.Seq.Int0", runFunction: { n in run_SetIsStrictSupersetSeqInt(setCD, arrayAB, false, 500 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setCD, arrayAB]) }), BenchmarkInfo( name: "Set.isStrictSuperset.Seq.Box0", runFunction: { n in run_SetIsStrictSupersetSeqBox(setOCD, arrayOAB, false, 500 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOCD, arrayOAB]) }), BenchmarkInfo( name: "Set.isStrictSuperset.Seq.Int25", runFunction: { n in run_SetIsStrictSupersetSeqInt(setB, arrayBC, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setB, arrayBC]) }), BenchmarkInfo( name: "Set.isStrictSuperset.Seq.Box25", runFunction: { n in run_SetIsStrictSupersetSeqBox(setOB, arrayOBC, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOB, arrayOBC]) }), BenchmarkInfo( name: "Set.isStrictSuperset.Seq.Int50", runFunction: { n in run_SetIsStrictSupersetSeqInt(setY, arrayYZ, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setY, arrayYZ]) }), BenchmarkInfo( name: "Set.isStrictSuperset.Seq.Int100", runFunction: { n in run_SetIsStrictSupersetSeqInt(setP, arrayP, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, arrayP]) }), BenchmarkInfo( name: "Set.isDisjoint.Empty.Int", runFunction: { n in run_SetIsDisjointInt(setE, setAB, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setE, setAB]) }), BenchmarkInfo( name: "Set.isDisjoint.Int.Empty", runFunction: { n in run_SetIsDisjointInt(setAB, setE, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setE]) }), BenchmarkInfo( name: "Set.isDisjoint.Empty.Box", runFunction: { n in run_SetIsDisjointBox(setOE, setOAB, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOE, setOAB]) }), BenchmarkInfo( name: "Set.isDisjoint.Box.Empty", runFunction: { n in run_SetIsDisjointBox(setOAB, setOE, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOE]) }), BenchmarkInfo( name: "Set.isDisjoint.Int0", runFunction: { n in run_SetIsDisjointInt(setAB, setCD, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }), BenchmarkInfo( name: "Set.isDisjoint.Box0", runFunction: { n in run_SetIsDisjointBox(setOAB, setOCD, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }), BenchmarkInfo( name: "Set.isDisjoint.Smaller.Int0", runFunction: { n in run_SetIsDisjointIntCommutative(setAB, setCDS, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCDS]) }), BenchmarkInfo( name: "Set.isDisjoint.Smaller.Box0", runFunction: { n in run_SetIsDisjointBoxCommutative(setOAB, setOCDS, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCDS]) }), BenchmarkInfo( name: "Set.isDisjoint.Int25", runFunction: { n in run_SetIsDisjointInt(setB, setAB, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setB, setAB]) }), BenchmarkInfo( name: "Set.isDisjoint.Box25", runFunction: { n in run_SetIsDisjointBox(setOB, setOAB, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOB, setOAB]) }), BenchmarkInfo( name: "Set.isDisjoint.Int50", runFunction: { n in run_SetIsDisjointInt(setY, setXY, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setY, setXY]) }), BenchmarkInfo( name: "Set.isDisjoint.Int100", runFunction: { n in run_SetIsDisjointInt(setP, setQ, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, setQ]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Empty.Int", runFunction: { n in run_SetIsDisjointSeqInt(setE, arrayAB, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setE, arrayAB]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Int.Empty", runFunction: { n in run_SetIsDisjointSeqInt(setAB, arrayE, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayE]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Empty.Box", runFunction: { n in run_SetIsDisjointSeqBox(setOE, arrayOAB, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOE, arrayOAB]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Box.Empty", runFunction: { n in run_SetIsDisjointSeqBox(setOAB, arrayOE, true, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOE]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Int0", runFunction: { n in run_SetIsDisjointSeqInt(setAB, arrayCD, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayCD]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Box0", runFunction: { n in run_SetIsDisjointSeqBox(setOAB, arrayOCD, true, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOCD]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Int25", runFunction: { n in run_SetIsDisjointSeqInt(setB, arrayAB, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setB, arrayAB]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Box25", runFunction: { n in run_SetIsDisjointSeqBox(setOB, arrayOAB, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOB, arrayOAB]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Int50", runFunction: { n in run_SetIsDisjointSeqInt(setY, arrayXY, false, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setY, arrayXY]) }), BenchmarkInfo( name: "Set.isDisjoint.Seq.Int100", runFunction: { n in run_SetIsDisjointSeqInt(setP, arrayP, false, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, arrayP]) }), BenchmarkInfo( name: "SetSymmetricDifferenceInt0", runFunction: { n in run_SetSymmetricDifferenceInt(setAB, setCD, countABCD, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }), BenchmarkInfo( name: "SetSymmetricDifferenceBox0", runFunction: { n in run_SetSymmetricDifferenceBox(setOAB, setOCD, countABCD, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }), BenchmarkInfo( name: "SetSymmetricDifferenceInt25", runFunction: { n in run_SetSymmetricDifferenceInt(setAB, setBC, countAC, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setBC]) }), BenchmarkInfo( name: "SetSymmetricDifferenceBox25", runFunction: { n in run_SetSymmetricDifferenceBox(setOAB, setOBC, countAC, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOBC]) }), BenchmarkInfo( name: "SetSymmetricDifferenceInt50", runFunction: { n in run_SetSymmetricDifferenceInt(setXY, setYZ, size, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setXY, setYZ]) }), BenchmarkInfo( name: "SetSymmetricDifferenceInt100", runFunction: { n in run_SetSymmetricDifferenceInt(setP, setQ, 0, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, setQ]) }), BenchmarkInfo( name: "SetIntersectionInt0", runFunction: { n in run_SetIntersectionInt(setAB, setCD, 0, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }), BenchmarkInfo( name: "SetIntersectionBox0", runFunction: { n in run_SetIntersectionBox(setOAB, setOCD, 0, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }), BenchmarkInfo( name: "SetIntersectionInt25", runFunction: { n in run_SetIntersectionInt(setAB, setBC, countB, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setBC]) }), BenchmarkInfo( name: "SetIntersectionBox25", runFunction: { n in run_SetIntersectionBox(setOAB, setOBC, countB, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOBC]) }), BenchmarkInfo( name: "SetIntersectionInt50", runFunction: { n in run_SetIntersectionInt(setXY, setYZ, half, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setXY, setYZ]) }), BenchmarkInfo( name: "SetIntersectionInt100", runFunction: { n in run_SetIntersectionInt(setP, setQ, size, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, setQ]) }), BenchmarkInfo( name: "Set.intersection.Seq.Int0", runFunction: { n in run_SetIntersectionSeqInt(setAB, arrayCD, 0, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayCD]) }), BenchmarkInfo( name: "Set.intersection.Seq.Box0", runFunction: { n in run_SetIntersectionSeqBox(setOAB, arrayOCD, 0, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOCD]) }), BenchmarkInfo( name: "Set.intersection.Seq.Int25", runFunction: { n in run_SetIntersectionSeqInt(setAB, arrayBC, countB, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayBC]) }), BenchmarkInfo( name: "Set.intersection.Seq.Box25", runFunction: { n in run_SetIntersectionSeqBox(setOAB, arrayOBC, countB, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOBC]) }), BenchmarkInfo( name: "Set.intersection.Seq.Int50", runFunction: { n in run_SetIntersectionSeqInt(setXY, arrayYZ, half, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setXY, arrayYZ]) }), BenchmarkInfo( name: "Set.intersection.Seq.Int100", runFunction: { n in run_SetIntersectionSeqInt(setP, arrayP, size, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, arrayP]) }), BenchmarkInfo( name: "SetUnionInt0", runFunction: { n in run_SetUnionInt(setAB, setCD, countABCD, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }), BenchmarkInfo( name: "SetUnionBox0", runFunction: { n in run_SetUnionBox(setOAB, setOCD, countABCD, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }), BenchmarkInfo( name: "SetUnionInt25", runFunction: { n in run_SetUnionInt(setAB, setBC, countABC, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setBC]) }), BenchmarkInfo( name: "SetUnionBox25", runFunction: { n in run_SetUnionBox(setOAB, setOBC, countABC, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOBC]) }), BenchmarkInfo( name: "SetUnionInt50", runFunction: { n in run_SetUnionInt(setXY, setYZ, size + half, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setXY, setYZ]) }), BenchmarkInfo( name: "SetUnionInt100", runFunction: { n in run_SetUnionInt(setP, setQ, size, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, setQ]) }), BenchmarkInfo( name: "Set.subtracting.Empty.Int", runFunction: { n in run_SetSubtractingInt(setE, setAB, 0, 1000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setE, setAB]) }), BenchmarkInfo( name: "Set.subtracting.Int.Empty", runFunction: { n in run_SetSubtractingInt(setAB, setE, countAB, 1000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setE]) }), BenchmarkInfo( name: "Set.subtracting.Empty.Box", runFunction: { n in run_SetSubtractingBox(setOE, setOAB, 0, 1000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOE, setOAB]) }), BenchmarkInfo( name: "Set.subtracting.Box.Empty", runFunction: { n in run_SetSubtractingBox(setOAB, setOE, countAB, 1000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOE]) }), BenchmarkInfo( name: "SetSubtractingInt0", runFunction: { n in run_SetSubtractingInt(setAB, setCD, countAB, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }), BenchmarkInfo( name: "SetSubtractingBox0", runFunction: { n in run_SetSubtractingBox(setOAB, setOCD, countAB, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }), BenchmarkInfo( name: "SetSubtractingInt25", runFunction: { n in run_SetSubtractingInt(setAB, setBC, countA, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setBC]) }), BenchmarkInfo( name: "SetSubtractingBox25", runFunction: { n in run_SetSubtractingBox(setOAB, setOBC, countA, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOBC]) }), BenchmarkInfo( name: "SetSubtractingInt50", runFunction: { n in run_SetSubtractingInt(setXY, setYZ, half, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setXY, setYZ]) }), BenchmarkInfo( name: "SetSubtractingInt100", runFunction: { n in run_SetSubtractingInt(setP, setQ, 0, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, setQ]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Empty.Int", runFunction: { n in run_SetSubtractingSeqInt(setE, arrayAB, 0, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setE, arrayAB]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Int.Empty", runFunction: { n in run_SetSubtractingSeqInt(setAB, arrayE, countAB, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayE]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Empty.Box", runFunction: { n in run_SetSubtractingSeqBox(setOE, arrayOAB, 0, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOE, arrayOAB]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Box.Empty", runFunction: { n in run_SetSubtractingSeqBox(setOAB, arrayOE, countAB, 5000 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOE]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Int0", runFunction: { n in run_SetSubtractingSeqInt(setAB, arrayCD, countAB, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayCD]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Box0", runFunction: { n in run_SetSubtractingSeqBox(setOAB, arrayOCD, countAB, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOCD]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Int25", runFunction: { n in run_SetSubtractingSeqInt(setAB, arrayBC, countA, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, arrayBC]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Box25", runFunction: { n in run_SetSubtractingSeqBox(setOAB, arrayOBC, countA, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, arrayOBC]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Int50", runFunction: { n in run_SetSubtractingSeqInt(setXY, arrayYZ, half, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setXY, arrayYZ]) }), BenchmarkInfo( name: "Set.subtracting.Seq.Int100", runFunction: { n in run_SetSubtractingSeqInt(setP, arrayP, 0, 50 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setP, arrayP]) }), BenchmarkInfo( name: "Set.filter.Int50.16k", runFunction: { n in run_SetFilterInt50(n) }, tags: [.validation, .api, .Set], setUpFunction: { set(16_000) }), BenchmarkInfo( name: "Set.filter.Int50.20k", runFunction: { n in run_SetFilterInt50(n) }, tags: [.validation, .api, .Set], setUpFunction: { set(20_000) }), BenchmarkInfo( name: "Set.filter.Int50.24k", runFunction: { n in run_SetFilterInt50(n) }, tags: [.validation, .api, .Set], setUpFunction: { set(24_000) }), BenchmarkInfo( name: "Set.filter.Int50.28k", runFunction: { n in run_SetFilterInt50(n) }, tags: [.validation, .api, .Set], setUpFunction: { set(28_000) }), BenchmarkInfo( name: "Set.filter.Int100.16k", runFunction: { n in run_SetFilterInt100(n) }, tags: [.validation, .api, .Set], setUpFunction: { set(16_000) }), BenchmarkInfo( name: "Set.filter.Int100.20k", runFunction: { n in run_SetFilterInt100(n) }, tags: [.validation, .api, .Set], setUpFunction: { set(20_000) }), BenchmarkInfo( name: "Set.filter.Int100.24k", runFunction: { n in run_SetFilterInt100(n) }, tags: [.validation, .api, .Set], setUpFunction: { set(24_000) }), BenchmarkInfo( name: "Set.filter.Int100.28k", runFunction: { n in run_SetFilterInt100(n) }, tags: [.validation, .api, .Set], setUpFunction: { set(28_000) }), // Legacy benchmarks, kept for continuity with previous releases. BenchmarkInfo( name: "SetExclusiveOr", // ~"SetSymmetricDifferenceInt0" runFunction: { n in run_SetSymmetricDifferenceInt(setAB, setCD, countABCD, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }, legacyFactor: 10), BenchmarkInfo( name: "SetExclusiveOr_OfObjects", // ~"SetSymmetricDifferenceBox0" runFunction: { n in run_SetSymmetricDifferenceBox(setOAB, setOCD, countABCD, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }, legacyFactor: 10), BenchmarkInfo( name: "SetIntersect", // ~"SetIntersectionInt0" runFunction: { n in run_SetIntersectionInt(setAB, setCD, 0, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }, legacyFactor: 10), BenchmarkInfo( name: "SetUnion", // ~"SetUnionInt0" runFunction: { n in run_SetUnionInt(setAB, setCD, countABCD, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setAB, setCD]) }, legacyFactor: 10), BenchmarkInfo( name: "SetUnion_OfObjects", // ~"SetUnionBox0" runFunction: { n in run_SetUnionBox(setOAB, setOCD, countABCD, 10 * n) }, tags: [.validation, .api, .Set], setUpFunction: { blackHole([setOAB, setOCD]) }, legacyFactor: 10), ] @inline(never) public func run_SetIsSubsetInt( _ a: Set<Int>, _ b: Set<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isSubset = a.isSubset(of: identity(b)) check(isSubset == r) } } @inline(never) public func run_SetIsSubsetSeqInt( _ a: Set<Int>, _ b: Array<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isSubset = a.isSubset(of: identity(b)) check(isSubset == r) } } @inline(never) public func run_SetIsStrictSubsetInt( _ a: Set<Int>, _ b: Set<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isStrictSubset = a.isStrictSubset(of: identity(b)) check(isStrictSubset == r) } } @inline(never) public func run_SetIsStrictSubsetSeqInt( _ a: Set<Int>, _ b: Array<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isStrictSubset = a.isStrictSubset(of: identity(b)) check(isStrictSubset == r) } } @inline(never) public func run_SetIsSupersetSeqInt( _ a: Set<Int>, _ b: Array<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isSuperset = a.isSuperset(of: identity(b)) check(isSuperset == r) } } @inline(never) public func run_SetIsStrictSupersetSeqInt( _ a: Set<Int>, _ b: Array<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isStrictSuperset = a.isStrictSuperset(of: identity(b)) check(isStrictSuperset == r) } } @inline(never) public func run_SetSymmetricDifferenceInt( _ a: Set<Int>, _ b: Set<Int>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let diff = a.symmetricDifference(identity(b)) check(diff.count == r) } } @inline(never) public func run_SetUnionInt( _ a: Set<Int>, _ b: Set<Int>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let or = a.union(identity(b)) check(or.count == r) } } @inline(never) public func run_SetIntersectionInt( _ a: Set<Int>, _ b: Set<Int>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let and = a.intersection(identity(b)) check(and.count == r) } } @inline(never) public func run_SetIntersectionSeqInt( _ a: Set<Int>, _ b: Array<Int>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let and = a.intersection(identity(b)) check(and.count == r) } } @inline(never) public func run_SetSubtractingInt( _ a: Set<Int>, _ b: Set<Int>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let and = a.subtracting(identity(b)) check(and.count == r) } } @inline(never) public func run_SetSubtractingSeqInt( _ a: Set<Int>, _ b: Array<Int>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let and = a.subtracting(identity(b)) check(and.count == r) } } @inline(never) public func run_SetIsDisjointInt( _ a: Set<Int>, _ b: Set<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isDisjoint = a.isDisjoint(with: identity(b)) check(isDisjoint == r) } } // Run isDisjoint Int switching the order of the two sets. @inline(never) public func run_SetIsDisjointIntCommutative( _ a: Set<Int>, _ b: Set<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isDisjointA = a.isDisjoint(with: identity(b)) check(isDisjointA == r) let isDisjointB = b.isDisjoint(with: identity(a)) check(isDisjointB == r) } } @inline(never) public func run_SetIsDisjointSeqInt( _ a: Set<Int>, _ b: Array<Int>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isDisjoint = a.isDisjoint(with: identity(b)) check(isDisjoint == r) } } @inline(never) public func run_SetFilterInt50(_ n: Int) { for _ in 0 ..< n { let half = set.filter { $0 % 2 == 0 } check(set.count == half.count * 2) } } @inline(never) public func run_SetFilterInt100(_ n: Int) { for _ in 0 ..< n { let copy = set.filter { _ in true } check(set.count == copy.count) } } class Box<T : Hashable> : Hashable { var value: T init(_ v: T) { value = v } func hash(into hasher: inout Hasher) { hasher.combine(value) } static func ==(lhs: Box, rhs: Box) -> Bool { return lhs.value == rhs.value } } @inline(never) func run_SetIsSubsetBox( _ a: Set<Box<Int>>, _ b: Set<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isSubset = a.isSubset(of: identity(b)) check(isSubset == r) } } @inline(never) func run_SetIsSubsetSeqBox( _ a: Set<Box<Int>>, _ b: Array<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isSubset = a.isSubset(of: identity(b)) check(isSubset == r) } } @inline(never) func run_SetIsStrictSubsetBox( _ a: Set<Box<Int>>, _ b: Set<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isStrictSubset = a.isStrictSubset(of: identity(b)) check(isStrictSubset == r) } } @inline(never) func run_SetIsStrictSubsetSeqBox( _ a: Set<Box<Int>>, _ b: Array<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isStrictSubset = a.isStrictSubset(of: identity(b)) check(isStrictSubset == r) } } @inline(never) func run_SetIsSupersetSeqBox( _ a: Set<Box<Int>>, _ b: Array<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isSuperset = a.isSuperset(of: identity(b)) check(isSuperset == r) } } @inline(never) func run_SetIsStrictSupersetSeqBox( _ a: Set<Box<Int>>, _ b: Array<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isStrictSuperset = a.isStrictSuperset(of: identity(b)) check(isStrictSuperset == r) } } @inline(never) func run_SetSymmetricDifferenceBox( _ a: Set<Box<Int>>, _ b: Set<Box<Int>>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let diff = a.symmetricDifference(identity(b)) check(diff.count == r) } } @inline(never) func run_SetUnionBox( _ a: Set<Box<Int>>, _ b: Set<Box<Int>>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let or = a.union(identity(b)) check(or.count == r) } } @inline(never) func run_SetIntersectionBox( _ a: Set<Box<Int>>, _ b: Set<Box<Int>>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let and = a.intersection(b) check(and.count == r) } } @inline(never) func run_SetIntersectionSeqBox( _ a: Set<Box<Int>>, _ b: Array<Box<Int>>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let and = a.intersection(identity(b)) check(and.count == r) } } @inline(never) func run_SetSubtractingBox( _ a: Set<Box<Int>>, _ b: Set<Box<Int>>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let and = a.subtracting(b) check(and.count == r) } } @inline(never) func run_SetSubtractingSeqBox( _ a: Set<Box<Int>>, _ b: Array<Box<Int>>, _ r: Int, _ n: Int) { for _ in 0 ..< n { let and = a.subtracting(identity(b)) check(and.count == r) } } @inline(never) func run_SetIsDisjointBox( _ a: Set<Box<Int>>, _ b: Set<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isDisjoint = a.isDisjoint(with: identity(b)) check(isDisjoint == r) } } // Run isDisjoint Box switching the order of the two sets. @inline(never) func run_SetIsDisjointBoxCommutative( _ a: Set<Box<Int>>, _ b: Set<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isDisjointA = a.isDisjoint(with: identity(b)) check(isDisjointA == r) let isDisjointB = b.isDisjoint(with: identity(a)) check(isDisjointB == r) } } @inline(never) func run_SetIsDisjointSeqBox( _ a: Set<Box<Int>>, _ b: Array<Box<Int>>, _ r: Bool, _ n: Int) { for _ in 0 ..< n { let isDisjoint = a.isDisjoint(with: identity(b)) check(isDisjoint == r) } }
apache-2.0
4f7e193be56138a8d770641f68f748be
33.244774
91
0.625849
3.264115
false
false
false
false
colemancda/HTTP-Server
Representor/HTTP/HTTPTransitionBuilder.swift
1
1274
public class HTTPTransitionBuilder : TransitionBuilderType { var attributes = InputProperties() var parameters = InputProperties() public var method = "POST" public var suggestedContentTypes: [String] = [] init() {} public func addAttribute<T : Any>( name: String, title: String? = nil, value: T? = nil, defaultValue: T? = nil, required: Bool? = nil) { let property = InputProperty<Any>( title: title, value: value, defaultValue: defaultValue, required: required ) attributes[name] = property } public func addAttribute(name: String, title: String? = nil, required: Bool? = nil) { let property = InputProperty<Any>(title: title, required: required) attributes[name] = property } public func addParameter(name: String) { let property = InputProperty<Any>(value: nil, defaultValue: nil) parameters[name] = property } public func addParameter<T : Any>(name: String, value: T?, defaultValue: T?, required: Bool? = nil) { let property = InputProperty<Any>(value: value, defaultValue: defaultValue, required: required) parameters[name] = property } }
mit
df2511d0ee43da5416530de72af11af3
24.48
105
0.609105
4.501767
false
false
false
false
WhisperSystems/Signal-iOS
Signal/src/Models/PhoneNumberValidator.swift
1
1534
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import SignalServiceKit @objc public enum ValidatedPhoneCountryCodes: UInt { case unitedStates = 1 case brazil = 55 } @objc public class PhoneNumberValidator: NSObject { @objc public func isValidForRegistration(phoneNumber: PhoneNumber) -> Bool { guard let countryCode = phoneNumber.getCountryCode() else { return false } guard let validatedCountryCode = ValidatedPhoneCountryCodes(rawValue: countryCode.uintValue) else { // no extra validation for this country return true } switch validatedCountryCode { case .brazil: return isValidForBrazilRegistration(phoneNumber: phoneNumber) case .unitedStates: return isValidForUnitedStatesRegistration(phoneNumber: phoneNumber) } } let validBrazilPhoneNumberRegex = try! NSRegularExpression(pattern: "^\\+55\\d{2}9?\\d{8}$", options: []) private func isValidForBrazilRegistration(phoneNumber: PhoneNumber) -> Bool { let e164 = phoneNumber.toE164() return validBrazilPhoneNumberRegex.hasMatch(input: e164) } let validUnitedStatesPhoneNumberRegex = try! NSRegularExpression(pattern: "^\\+1\\d{10}$", options: []) private func isValidForUnitedStatesRegistration(phoneNumber: PhoneNumber) -> Bool { let e164 = phoneNumber.toE164() return validUnitedStatesPhoneNumberRegex.hasMatch(input: e164) } }
gpl-3.0
4a10a89b77a9ad14f8522c3a4f4afcb5
31.638298
109
0.691004
4.85443
false
false
false
false
NGeenLibraries/NGeen
NGeen/Base/Constants/Constants.swift
1
1648
// // Constants.swift // Copyright (c) 2014 NGeen // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit let kCacheFileName: String = "NGeenCache.db" let kCacheFolder: String = "NGeenCache" let kDefaultServerName: String = "__kDefaultServerName" let kNGeenResponseSerializationErrorDomain: String = "com.ngeen.error.serialization.response"; let kMaxDiskCacheCapacity = 10 * 1024 * 1024; // 10MB let kMaxMemoryCacheCapacity = 8 * 1024 * 1024; // 8MB let kNGeenDownloadTaskDidFailToMoveFileNotification = "__NGeenDownloadTaskDidFailToMoveFileNotification" let kTestUrl: NSURL = NSURL(string: "https://httpbin.org/")
mit
874a87563f4b6dc1c9003fe648c123e2
50.53125
104
0.774272
4.26943
false
false
false
false
SanctionCo/pilot-ios
Pods/ImagePicker/Source/CameraView/CameraMan.swift
4
6272
import Foundation import AVFoundation import PhotosUI protocol CameraManDelegate: class { func cameraManNotAvailable(_ cameraMan: CameraMan) func cameraManDidStart(_ cameraMan: CameraMan) func cameraMan(_ cameraMan: CameraMan, didChangeInput input: AVCaptureDeviceInput) } class CameraMan { weak var delegate: CameraManDelegate? let session = AVCaptureSession() let queue = DispatchQueue(label: "no.hyper.ImagePicker.Camera.SessionQueue") var backCamera: AVCaptureDeviceInput? var frontCamera: AVCaptureDeviceInput? var stillImageOutput: AVCaptureStillImageOutput? var startOnFrontCamera: Bool = false deinit { stop() } // MARK: - Setup func setup(_ startOnFrontCamera: Bool = false) { self.startOnFrontCamera = startOnFrontCamera checkPermission() } func setupDevices() { // Input AVCaptureDevice .devices() .filter { return $0.hasMediaType(AVMediaType.video) }.forEach { switch $0.position { case .front: self.frontCamera = try? AVCaptureDeviceInput(device: $0) case .back: self.backCamera = try? AVCaptureDeviceInput(device: $0) default: break } } // Output stillImageOutput = AVCaptureStillImageOutput() stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG] } func addInput(_ input: AVCaptureDeviceInput) { configurePreset(input) if session.canAddInput(input) { session.addInput(input) DispatchQueue.main.async { self.delegate?.cameraMan(self, didChangeInput: input) } } } // MARK: - Permission func checkPermission() { let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) switch status { case .authorized: start() case .notDetermined: requestPermission() default: delegate?.cameraManNotAvailable(self) } } func requestPermission() { AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in DispatchQueue.main.async { if granted { self.start() } else { self.delegate?.cameraManNotAvailable(self) } } } } // MARK: - Session var currentInput: AVCaptureDeviceInput? { return session.inputs.first as? AVCaptureDeviceInput } fileprivate func start() { // Devices setupDevices() guard let input = (self.startOnFrontCamera) ? frontCamera ?? backCamera : backCamera, let output = stillImageOutput else { return } addInput(input) if session.canAddOutput(output) { session.addOutput(output) } queue.async { self.session.startRunning() DispatchQueue.main.async { self.delegate?.cameraManDidStart(self) } } } func stop() { self.session.stopRunning() } func switchCamera(_ completion: (() -> Void)? = nil) { guard let currentInput = currentInput else { completion?() return } queue.async { guard let input = (currentInput == self.backCamera) ? self.frontCamera : self.backCamera else { DispatchQueue.main.async { completion?() } return } self.configure { self.session.removeInput(currentInput) self.addInput(input) } DispatchQueue.main.async { completion?() } } } func takePhoto(_ previewLayer: AVCaptureVideoPreviewLayer, location: CLLocation?, completion: (() -> Void)? = nil) { guard let connection = stillImageOutput?.connection(with: AVMediaType.video) else { return } connection.videoOrientation = Helper.videoOrientation() queue.async { self.stillImageOutput?.captureStillImageAsynchronously(from: connection) { buffer, error in guard let buffer = buffer, error == nil && CMSampleBufferIsValid(buffer), let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer), let image = UIImage(data: imageData) else { DispatchQueue.main.async { completion?() } return } self.savePhoto(image, location: location, completion: completion) } } } func savePhoto(_ image: UIImage, location: CLLocation?, completion: (() -> Void)? = nil) { PHPhotoLibrary.shared().performChanges({ let request = PHAssetChangeRequest.creationRequestForAsset(from: image) request.creationDate = Date() request.location = location }, completionHandler: { (_, _) in DispatchQueue.main.async { completion?() } }) } func flash(_ mode: AVCaptureDevice.FlashMode) { guard let device = currentInput?.device, device.isFlashModeSupported(mode) else { return } queue.async { self.lock { device.flashMode = mode } } } func focus(_ point: CGPoint) { guard let device = currentInput?.device, device.isFocusModeSupported(AVCaptureDevice.FocusMode.locked) else { return } queue.async { self.lock { device.focusPointOfInterest = point } } } func zoom(_ zoomFactor: CGFloat) { guard let device = currentInput?.device, device.position == .back else { return } queue.async { self.lock { device.videoZoomFactor = zoomFactor } } } // MARK: - Lock func lock(_ block: () -> Void) { if let device = currentInput?.device, (try? device.lockForConfiguration()) != nil { block() device.unlockForConfiguration() } } // MARK: - Configure func configure(_ block: () -> Void) { session.beginConfiguration() block() session.commitConfiguration() } // MARK: - Preset func configurePreset(_ input: AVCaptureDeviceInput) { for asset in preferredPresets() { if input.device.supportsSessionPreset(AVCaptureSession.Preset(rawValue: asset)) && self.session.canSetSessionPreset(AVCaptureSession.Preset(rawValue: asset)) { self.session.sessionPreset = AVCaptureSession.Preset(rawValue: asset) return } } } func preferredPresets() -> [String] { return [ AVCaptureSession.Preset.high.rawValue, AVCaptureSession.Preset.high.rawValue, AVCaptureSession.Preset.low.rawValue ] } }
mit
9262019efcff710baba44e2fe5e55ecc
24.088
165
0.647481
4.787786
false
false
false
false
tresorit/ZeroKit-Realm-encrypted-tasks
ios/RealmTasks iOS/MySharesViewController.swift
1
11009
import UIKit import Realm import RealmSwift import ZeroKit class MySharesViewController: ShareBaseTableViewController { var alert: UIAlertController? override func awakeFromNib() { super.awakeFromNib() self.title = "My Shares" } override func viewDidLoad() { super.viewDidLoad() realm = sharesRealm()! tokens.append(realm.addNotificationBlock { [weak self] _, _ in self?.updateList() }) updateList() } private func updateList() { items = realm?.objects(User.self).sorted(byKeyPath: "userName") tableView.reloadData() } @IBAction func addButtonTap(_ sender: Any) { let alert = UIAlertController(title: "Share My Tasks", message: "Enter user name to share:", preferredStyle: .alert) alert.addTextField(configurationHandler: nil) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Share", style: .default, handler: { [weak self, weak alert] _ in let username = alert?.textFields?.first?.text ?? "" self?.share(with: username) })) present(alert, animated: true, completion: nil) } private func share(with username: String) { let errorHandler = { [weak self] (message: String) in self?.dismissMessage { self?.showError(title: "Error sharing with user '\(username)'.", message: message) } } present(message: "Sharing...") getUserObjects(for: username) { myUser, otherUser, error in guard let myUser = myUser, let otherUser = otherUser else { errorHandler("Failed to get user IDs.") return } guard myUser.realmUserId! != otherUser.realmUserId! else { errorHandler("You cannot share with yourself.") return } try! self.realm.write { self.realm.create(User.self, value: otherUser, update: true) } let permission = self.realmPermission(for: otherUser.realmUserId!) SyncUser.current?.applyPermission(permission) { error in guard error == nil else { errorHandler("Failed to add permission for realmtasks realm.") return } let tresorId = (try! Realm()).objects(TaskListList.self).first!.tresorId! self.shareTresor(tresorId: tresorId, userId: otherUser.zerokitUserId!) { error in guard error == nil else { errorHandler("Failed sharing tresor.") return } let invitesPublic = invitesPublicRealm(for: otherUser.realmUserId!)! try! invitesPublic.write { invitesPublic.create(User.self, value: myUser, update: true) } invitesPublic.refresh() self.dismissMessage() } } } } private func revokeAccess(from username: String) { let errorHandler = { [weak self] (message: String) in self?.dismissMessage { self?.showError(title: "Error revoking access from user '\(username)'.", message: message) } } present(message: "Revoking access...") getUserObjects(for: username) { myUser, otherUser, error in guard let myUser = myUser, let otherUser = otherUser else { errorHandler("Failed to get users.") return } guard myUser.realmUserId! != otherUser.realmUserId! else { errorHandler("You cannot revoke access from yourself.") return } // Set ID empty when revoking access myUser.zerokitUserId = "" let invitesPublic = invitesPublicRealm(for: otherUser.realmUserId!)! try! invitesPublic.write { invitesPublic.create(User.self, value: myUser, update: true) } invitesPublic.refresh() let tresorId = (try! Realm()).objects(TaskListList.self).first!.tresorId! self.kickUser(userId: otherUser.zerokitUserId!, from: tresorId) { error in guard error == nil else { errorHandler("Failed to kick user from tresor.") return } let permission = self.realmPermission(for: otherUser.realmUserId!) SyncUser.current?.revokePermission(permission) { _ in // guard error == nil else { // errorHandler("Failed to revoke permission from realmtasks realm.") // return // } try! self.realm.write { let result = self.realm.objects(User.self).filter("realmUserId == %@", otherUser.realmUserId!) if result.count > 0 { self.realm.delete(result) } } self.dismissMessage() } } } } private func getUserObjects(for username: String, completion: @escaping (User?, User?, Error?) -> Void) { ZeroKitManager.shared.backend.getProfile { profile, error in guard let profile = profile, let profileData = profile.data(using: .utf8), let json = (try? JSONSerialization.jsonObject(with: profileData, options: [])) as? [String: Any], let myUsername = json[ProfileField.alias.rawValue] as? String else { completion(nil, nil, error) return } ZeroKitManager.shared.zeroKit.whoAmI { myUserId, error in guard let myUserId = myUserId, let myRealmId = SyncUser.current?.identity else { completion(nil, nil, error) return } let myUser = User() myUser.userName = myUsername myUser.realmUserId = myRealmId myUser.zerokitUserId = myUserId self.getOtherUser(for: username) { otherUser, error in guard let otherUser = otherUser else { completion(nil, nil, error) return } completion(myUser, otherUser, nil) } } } } private func getOtherUser(for username: String, completion: @escaping (User?, Error?) -> Void) { ZeroKitManager.shared.backend.getUserId(forUsername: ZeroKitAuth.testUsername(from: username)) { userId, error in guard let userId = userId else { completion(nil, error) return } self.getRealmUserId(for: userId) { realmUserId, error in if let realmUserId = realmUserId { let user = User() user.userName = username user.realmUserId = realmUserId user.zerokitUserId = userId completion(user, nil) } else { completion(nil, error) } } } } private func getRealmUserId(for zeroKitUserId: String, completion: @escaping (String?, Error?) -> Void) { ZeroKitManager.shared.backend.getPublicProfile(for: zeroKitUserId) { profileStr, error in guard let data = profileStr?.data(using: .utf8), let json = try? JSONSerialization.jsonObject(with: data, options: []), let dict = json as? [String: Any], let realmUserId = dict[PublicProfileField.realmUserId.rawValue] as? String else { completion(nil, error) return } completion(realmUserId, nil) } } private func realmPermission(for realmUserId: String) -> RLMSyncPermissionValue { let defaultRealm = try! Realm() let path = defaultRealm.configuration.syncConfiguration!.realmURL.path let permission = RLMSyncPermissionValue(realmPath: path, userID: realmUserId, accessLevel: .write) return permission } private func shareTresor(tresorId: String, userId: String, completion: @escaping (Error?) -> Void) { ZeroKitManager.shared.zeroKit.share(tresorWithId: tresorId, withUser: userId) { operationId, error in if let operationId = operationId { ZeroKitManager.shared.backend.sharedTresor(operationId: operationId) { error in completion(error) } } else if error! == ZeroKitError.alreadyMember { completion(nil) } else { completion(error) } } } private func kickUser(userId: String, from tresorId: String, completion: @escaping (Error?) -> Void) { ZeroKitManager.shared.zeroKit.kick(userWithId: userId, fromTresor: tresorId) { operationId, error in if let operationId = operationId { ZeroKitManager.shared.backend.kickedUser(operationId: operationId) { error in completion(error) } } else if error! == ZeroKitError.notMember { completion(nil) } else { completion(error) } } } func showError(title: String, message: String?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } func present(message: String) { func present() { self.alert = UIAlertController(title: message, message: nil, preferredStyle: .alert) self.present(self.alert!, animated: true, completion: nil) } if let alert = alert { alert.dismiss(animated: false, completion: present) } else { present() } } func dismissMessage(completion: ((Void) -> Void)? = nil) { alert?.dismiss(animated: true, completion: completion) alert = nil } // MARK: - Table view data source override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let user = items![indexPath.row] self.revokeAccess(from: user.userName!) } tableView.reloadData() } }
bsd-3-clause
e8e565d2e61567f1fb871d0e840b6047
38.317857
136
0.551276
5.052318
false
false
false
false
eljeff/AudioKit
Tests/AudioKitTests/Operation Tests/Effect Tests/bitcrushOperationTests.swift
2
1507
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AudioKit import XCTest class BitcrushTests: XCTestCase { func testBitDepth() { let engine = AudioEngine() let input = Oscillator() engine.output = OperationEffect(input) { $0.bitCrush(bitDepth: 7) } input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testDefault() { let engine = AudioEngine() let input = Oscillator() engine.output = OperationEffect(input) { $0.bitCrush() } input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testParameters() { let engine = AudioEngine() let input = Oscillator() engine.output = OperationEffect(input) { $0.bitCrush(bitDepth: 7, sampleRate: 4_000) } input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } func testSampleRate() { let engine = AudioEngine() let input = Oscillator() engine.output = OperationEffect(input) { $0.bitCrush(sampleRate: 4_000) } input.start() let audio = engine.startTest(totalDuration: 1.0) audio.append(engine.render(duration: 1.0)) testMD5(audio) } }
mit
6d27758be7a59c9bfb51ebf01f1dfd4a
30.395833
100
0.620438
4.061995
false
true
false
false
WSDOT/wsdot-ios-app
wsdot/RouteDeparturesViewController.swift
1
18491
// // RouteDetailsViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import UIKit import GoogleMobileAds import RealmSwift class RouteDeparturesViewController: UIViewController, GADBannerViewDelegate { let timesViewSegue = "timesViewSegue" let camerasViewSegue = "camerasViewSegue" let vesselWatchSegue = "vesselWatchSegue" let locationManager = CLLocationManager() let segueDepartureDaySelectionViewController = "DepartureDaySelectionViewController" let segueTerminalSelectionViewController = "TerminalSelectionViewController" let SegueRouteAlertsViewController = "RouteAlertsViewController" @IBOutlet weak var timesContainerView: UIView! @IBOutlet weak var camerasContainerView: UIView! @IBOutlet weak var vesselWatchContainerView: UIView! @IBOutlet weak var segmentedControl: UISegmentedControl! var routeTimesVC: RouteTimesViewController! var routeCamerasVC: RouteCamerasViewController! @IBOutlet weak var sailingButton: IconButton! @IBOutlet weak var dayButton: IconButton! @IBOutlet weak var bannerView: GAMBannerView! var routeItem: FerryScheduleItem? var routeId = 0 var selectedTerminal = 0 var overlayView = UIView() let favoriteBarButton = UIBarButtonItem() let alertBarButton = UIBarButtonItem() internal func adViewDidReceiveAd(_ bannerView: GAMBannerView) { print("wsdot debug: adViewDidReceiveAd") if let responseInfo = bannerView.responseInfo { print("wsdot debug: \(responseInfo)") print("wsdot debug: \(String(describing: responseInfo.adNetworkClassName))") print("wsdot debug: \(String(describing: responseInfo.responseIdentifier))") } } /* func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) { print("wsdot debug: didFailToReceiveAdWithError: \(error.localizedDescription)") // GADBannerView has the responseInfo property but this demonstrates accessing // response info from a returned NSError. if let responseInfo = error.userInfo[GADErrorUserInfoKeyResponseInfo] as? GADResponseInfo { print("wsdot debug: \(responseInfo)") } } */ override func viewDidLoad() { super.viewDidLoad() self.camerasContainerView.isHidden = true self.vesselWatchContainerView.isHidden = true sailingButton.setTitleColor(UIColor.lightText, for: .highlighted) sailingButton.layer.cornerRadius = 6.0 sailingButton.contentHorizontalAlignment = .left sailingButton.titleLabel?.minimumScaleFactor = 0.5 sailingButton.titleLabel?.adjustsFontSizeToFitWidth = true dayButton.setTitleColor(UIColor.lightText, for: .highlighted) dayButton.layer.cornerRadius = 6.0 dayButton.contentHorizontalAlignment = .center dayButton.titleLabel?.minimumScaleFactor = 0.5 dayButton.titleLabel?.adjustsFontSizeToFitWidth = true // Favorite button self.favoriteBarButton.action = #selector(RouteDeparturesViewController.updateFavorite(_:)) self.favoriteBarButton.target = self self.favoriteBarButton.tintColor = Colors.yellow self.favoriteBarButton.image = UIImage(named: "icStarSmall") self.favoriteBarButton.accessibilityLabel = "add to favorites" self.alertBarButton.image = UIImage(named: "icAlert") self.alertBarButton.accessibilityLabel = "Ferry Alert Bulletins" self.alertBarButton.action = #selector(RouteDeparturesViewController.openAlerts(_:)) self.navigationItem.rightBarButtonItems = [self.favoriteBarButton, self.alertBarButton] loadSailings() // Ad Banner let ferryRouteTarget = WSDOTAdTargets.ferryTargets[routeId] bannerView.adSize = getFullWidthAdaptiveAdSize() bannerView.adUnitID = ApiKeys.getAdId() bannerView.rootViewController = self let request = GAMRequest() request.customTargeting = [ "wsdotapp":"ferries", "wsdotferries":ferryRouteTarget ?? "ferries-home" ] bannerView.load(request) bannerView.delegate = self } @IBAction func sailingsButtonTap(_ sender: IconButton) { performSegue(withIdentifier: segueTerminalSelectionViewController, sender: self) } @IBAction func dayButtonTap(_ sender: Any) { // performSegue(withIdentifier: segueDepartureDaySelectionViewController, sender: self) // Ferry Schedule Calendar Message let alert = UIAlertController(title: "Ferry Schedule Calendar", message: "Many of the sailings continue to operate on reduced or alternate schedules. In order to provide up-to-date information, the mobile app ferry schedule calendar is now limited to daily schedules.\n\nTo view a future sailing time for your route please visit the schedule page online.", preferredStyle: .alert); alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)); let action: UIAlertAction = UIAlertAction(title: "Ferry Website", style: .default, handler: { (action) in UIApplication.shared.open(URL(string: "https://wsdot.com/ferries/schedule/")!, options: [:], completionHandler: nil) }) alert.addAction(action) alert.view.tintColor = Colors.tintColor self.present(alert, animated: true, completion: nil) } func loadSailings() { FerryRealmStore.updateRouteSchedules(false, completion: { error in if (error == nil) { self.routeItem = FerryRealmStore.findSchedule(withId: self.routeId) if let routeItemValue = self.routeItem { // Set sailings for RouteTimesVC self.routeTimesVC.currentSailing = routeItemValue.terminalPairs[0] self.routeTimesVC.sailingsByDate = routeItemValue.scheduleDates let dateFormater = DateFormatter() dateFormater.dateFormat = "EEE, MMM dd" let currentDate = dateFormater.string(from: Date()) if let firstSailingDateValue = routeItemValue.scheduleDates.first { self.routeTimesVC.dateData = TimeUtils.nextNDayDates(n: routeItemValue.scheduleDates.count, firstSailingDateValue.date) self.dayButton.setTitle(currentDate, for: UIControl.State()) // self.dayButton.setTitle(TimeUtils.getDayOfWeekString(self.routeTimesVC.dateData[self.routeTimesVC.currentDay]), for: UIControl.State()) } self.routeTimesVC.setDisplayedSailing(0) // set terminal for CamerasVC self.routeCamerasVC.departingTerminalId = self.getDepartingId() self.routeCamerasVC.refresh(true) // add aldert badge if(routeItemValue.routeAlerts.count > 0){ let customAlertButton = UIButton(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) let menuImage = UIImage(named: "icAlert") let templateImage = menuImage?.withRenderingMode(.alwaysTemplate) customAlertButton.setBackgroundImage(templateImage, for: .normal) customAlertButton.addTarget(self, action: #selector(self.openAlerts(_:)), for: .touchUpInside) customAlertButton.addSubview(UIHelpers.getBadgeLabel(text: "\(routeItemValue.routeAlerts.count)", color: UIColor.orange)) self.alertBarButton.customView = customAlertButton } self.title = routeItemValue.routeDescription if (routeItemValue.terminalPairs.count == 2) { self.sailingButton.setTitle("Departing \(routeItemValue.terminalPairs[0].aTerminalName)", for: UIControl.State()) } else { self.sailingButton.setTitle("\(routeItemValue.terminalPairs[0].aTerminalName) to \(routeItemValue.terminalPairs[0].bTterminalName)", for: UIControl.State()) } if (routeItemValue.selected){ self.favoriteBarButton.image = UIImage(named: "icStarSmallFilled") self.favoriteBarButton.accessibilityLabel = "remove from favorites" } else { self.favoriteBarButton.image = UIImage(named: "icStarSmall") self.favoriteBarButton.accessibilityLabel = "add to favorites" } self.locationManager.delegate = self self.locationManager.requestWhenInUseAuthorization() self.locationManager.startUpdatingLocation() } else { self.navigationItem.rightBarButtonItem = nil let alert = AlertMessages.getSingleActionAlert("Route Unavailable", message: "", confirm: "OK", comfirmHandler: { action in self.navigationController!.popViewController(animated: true) }) self.present(alert, animated: true, completion: nil) } } else { AlertMessages.getConnectionAlert(backupURL: WsdotURLS.ferries, message: "can't download departures") } }) } // Method called by DepartureDaySelctionVC // Pass the selected day index from DepartureDaySelectionVC to the RouteTimesVC func daySelected(_ index: Int) { routeTimesVC.changeDay(index) dayButton.setTitle(TimeUtils.getDayOfWeekString(routeTimesVC.dateData[routeTimesVC.currentDay]), for: UIControl.State()) } func terminalSelected(_ index: Int) { selectedTerminal = index let terminal = self.routeItem!.terminalPairs[index] routeTimesVC.changeTerminal(terminal) if (self.routeItem!.terminalPairs.count == 2){ sailingButton.setTitle("Departing \(terminal.aTerminalName)", for: UIControl.State()) } else { sailingButton.setTitle("\(terminal.aTerminalName) to \(terminal.bTterminalName)", for: UIControl.State()) } routeTimesVC.refresh(scrollToCurrentSailing: true) routeCamerasVC.departingTerminalId = terminal.aTerminalId routeCamerasVC.refresh(false) } // MARK - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Save a reference to this VC for passing it days and sailings if segue.identifier == timesViewSegue { routeTimesVC = segue.destination as? RouteTimesViewController routeTimesVC.routeId = self.routeId } if segue.identifier == SegueRouteAlertsViewController { let dest: RouteAlertsViewController = segue.destination as! RouteAlertsViewController dest.title = routeItem!.routeDescription + " Alerts" dest.routeId = routeId } if segue.identifier == vesselWatchSegue { let dest: VesselWatchViewController = segue.destination as! VesselWatchViewController dest.routeId = routeId } if segue.identifier == camerasViewSegue { routeCamerasVC = segue.destination as? RouteCamerasViewController } if segue.identifier == segueDepartureDaySelectionViewController { let destinationViewController = segue.destination as! DepartureDaySelectionViewController destinationViewController.my_parent = self destinationViewController.date_data = routeTimesVC.dateData destinationViewController.selectedIndex = routeTimesVC.currentDay } if segue.identifier == segueTerminalSelectionViewController { let destinationViewController = segue.destination as! TerminalSelectionViewController destinationViewController.my_parent = self if (self.routeItem!.terminalPairs.count == 2) { destinationViewController.menu_options = self.routeItem!.terminalPairs.map { return "Departing \($0.aTerminalName)" } } else { destinationViewController.menu_options = self.routeItem!.terminalPairs.map { return "\($0.aTerminalName) to \($0.bTterminalName)" } } destinationViewController.selectedIndex = selectedTerminal } } @IBAction func indexChanged(_ sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { UIView.animate(withDuration: 0.3, animations: { self.timesContainerView.isHidden = false self.camerasContainerView.isHidden = true self.vesselWatchContainerView.isHidden = true self.dayButton.isHidden = false self.sailingButton.isHidden = false }) } else if sender.selectedSegmentIndex == 1 { UIView.animate(withDuration: 0.3, animations: { self.timesContainerView.isHidden = true self.camerasContainerView.isHidden = false self.vesselWatchContainerView.isHidden = true self.dayButton.isHidden = true self.sailingButton.isHidden = false }) } else if sender.selectedSegmentIndex == 2 { UIView.animate(withDuration: 0.3, animations: { self.timesContainerView.isHidden = true self.camerasContainerView.isHidden = true self.vesselWatchContainerView.isHidden = false self.dayButton.isHidden = true self.sailingButton.isHidden = true }) } } // MARK: - // MARK: Helper functions fileprivate func getDepartingId() -> Int{ // get sailings for selected day let sailings = self.routeItem!.scheduleDates[0].sailings // get sailings for current route for sailing in sailings { if ((sailing.departingTerminalId == routeItem!.terminalPairs[0].aTerminalId)) { return sailing.departingTerminalId } } return -1 } /** * Method name: openAlerts * Description: called when user taps an alert button on a route cell. */ @objc func openAlerts(_ sender: UIButton){ performSegue(withIdentifier: SegueRouteAlertsViewController, sender: sender) } @objc func updateFavorite(_ sender: UIBarButtonItem) { let isFavorite = FerryRealmStore.toggleFavorite(routeId) if (isFavorite == 1){ favoriteBarButton.image = UIImage(named: "icStarSmallFilled") favoriteBarButton.accessibilityLabel = "remove from favorites" } else if (isFavorite == 0) { favoriteBarButton.image = UIImage(named: "icStarSmall") favoriteBarButton.accessibilityLabel = "add to favorites" } else { print("favorites write error") } } } extension RouteDeparturesViewController: CLLocationManagerDelegate { // MARK: CLLocationManagerDelegate methods func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { // if we can't get a location right away bail out of opertaion guard let usersLocation = manager.location else { manager.stopUpdatingLocation() return } let userLat: Double = usersLocation.coordinate.latitude let userLon: Double = usersLocation.coordinate.longitude // bail out if we don't have a route item set for some reason guard let route = routeItem else { manager.stopUpdatingLocation() return } // get map with terminal locations let terminalsMap = FerriesConsts.init().terminalMap // assume first terminal is closest var closetTerminalIndex = 0 var nearestDistance = -1 for (index, terminalPair) in route.terminalPairs.enumerated() { // check how close user is to terminal A in each pair let terminal = terminalsMap[terminalPair.aTerminalId] if let terminalAValue = terminal { let distanceA = LatLonUtils.haversine(userLat, lonA: userLon, latB: terminalAValue.latitude, lonB:terminalAValue.longitude) if distanceA < nearestDistance || nearestDistance < 0 { nearestDistance = distanceA closetTerminalIndex = index } } } terminalSelected(closetTerminalIndex) manager.stopUpdatingLocation() } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { //print("failed to get location") } func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { manager.startUpdatingLocation() } } }
gpl-3.0
11a84475030a18efb11b1eab3e7aa1aa
41.313501
389
0.631064
5.331892
false
false
false
false
jamesjmtaylor/weg-ios
weg-ios/Equipment/EquipmentViewController.swift
1
8805
// // EquipmentViewController.swift // weg-ios // // Created by Taylor, James on 4/29/18. // Copyright © 2018 James JM Taylor. All rights reserved. // import UIKit class EquipmentViewController: UIViewController{ @IBOutlet weak var photoImageView: UIImageView! @IBOutlet weak var groupImageView: UIImageView! @IBOutlet weak var individualImageView: UIImageView! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var stackViewHeight: NSLayoutConstraint! @IBOutlet weak var descriptionLabel: UILabel! var equipmentToView : Equipment? override func viewDidLoad() { super.viewDidLoad() saveEquipmentView(equipmentName: equipmentToView?.name ?? "No name", category: equipmentToView?.type.rawValue ?? "No category") configureViewToEquipmentType(item: equipmentToView) EquipmentRepository.setImage(photoImageView, equipmentToView?.photoUrl) } func configureViewToEquipmentType(item: Equipment?){ self.navigationItem.title = item?.name let formattedString = NSMutableAttributedString() if let item = item as? Gun { EquipmentRepository.setImage(groupImageView, item.groupIconUrl) EquipmentRepository.setImage(individualImageView, item.individualIconUrl) formattedString.bold("Description: ").normal(item.desc ?? "") descriptionLabel.attributedText = formattedString setDetailViews(gun: item) } else if let item = item as? Land { EquipmentRepository.setImage(groupImageView, item.groupIconUrl) EquipmentRepository.setImage(individualImageView, item.individualIconUrl) formattedString.bold("Description: ").normal(item.desc ?? "") descriptionLabel.attributedText = formattedString setDetailViews(land: item) } else if let item = item as? Sea { EquipmentRepository.setImage(individualImageView, item.individualIconUrl) formattedString.bold("Description: ").normal(item.desc ?? "") descriptionLabel.attributedText = formattedString groupImageView?.isHidden = true setDetailViews(sea: item) } else if let item = item as? Air { EquipmentRepository.setImage(groupImageView, item.groupIconUrl) EquipmentRepository.setImage(individualImageView, item.individualIconUrl) formattedString.bold("Description: ").normal(item.desc ?? "") descriptionLabel.attributedText = formattedString setDetailViews(air: item) } adjustStackViewHeight(stackViewHeight: self.stackViewHeight, numRows: self.numRows, rowHeight: self.rowHeight) } // MARK: - Detail Row Logic var numRows = 0 var rowHeight = 28 func createDetailRow(_ title: String, _ value: String, _ header: Bool = false) { guard let detailRowView = Bundle.main.loadNibNamed("EquipmentDetailRow", owner: self, options: nil)?.first as? EquipmentDetailRow else {return} let frame = CGRect(x: 0, y: 0, width: Int(self.view.frame.width), height: rowHeight) detailRowView.frame = frame detailRowView.configure(title: title, value: value, header: header) self.stackView.addArrangedSubview(detailRowView) numRows += 1 } func adjustStackViewHeight(stackViewHeight: NSLayoutConstraint, numRows: Int, rowHeight: Int){ stackViewHeight.constant = CGFloat(numRows * rowHeight) stackView.layoutIfNeeded() } func setDetailViews(gun: Gun){ if (gun.range > 0 ) {createDetailRow("Range",gun.range.description+" meters")} if (gun.altitude > 0 ) {createDetailRow("Altitude",gun.altitude.description+" meters")} if (gun.penetration > 0 ) {createDetailRow("Penetration",gun.penetration.description+"mm")} } func setDetailViews(land: Land){ if let it = land.primaryWeapon { createDetailRow("Primary Weapon",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} if (it.altitude > 0){createDetailRow("Altitude",it.altitude.description+" meters") } if (it.penetration > 0){createDetailRow("Penetration",it.penetration.description+"mm") } } if let it = land.secondaryWeapon { createDetailRow("Secondary Weapon",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} if (it.altitude > 0){createDetailRow("Altitude",it.altitude.description+" meters") } if (it.penetration > 0){createDetailRow("Penetration",it.penetration.description+"mm") } } if let it = land.atgm { createDetailRow("ATGM",it.name ?? "", true) createDetailRow("Range",it.range.description+" meters") createDetailRow("Penetration",it.penetration.description+"mm") } if (land.armor > 0){createDetailRow("Armor",land.armor.description+"mm", true)} if (land.speed > 0){createDetailRow("Speed",land.speed.description+" kph", true)} if (land.auto > 0){createDetailRow("Autonomy",land.auto.description+" km", true)} if (land.weight > 0){createDetailRow("Weight",land.weight.description+" tons", true)} } func setDetailViews(sea: Sea){ if let it = sea.gun { createDetailRow("Deck Gun",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} if (it.altitude > 0){createDetailRow("Altitude",it.altitude.description+" meters")} if (it.penetration > 0){createDetailRow("Penetration",it.penetration.description+"mm")} } if let it = sea.asm { createDetailRow("Anti-Ship Missile",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} if (it.altitude > 0){createDetailRow("Altitude",it.altitude.description+" meters") } if (it.penetration > 0){createDetailRow("Penetration",it.penetration.description+"mm") } } if let it = sea.sam { createDetailRow("Surface-to-Air Missile",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} if (it.altitude > 0){createDetailRow("Altitude",it.altitude.description+" meters") } if (it.penetration > 0){createDetailRow("Penetration",it.penetration.description+"mm") } } if let it = sea.torpedo { createDetailRow("Torpedo",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} } if ((sea.transports?.isEmpty ?? true || sea.transports?.contains("null") ?? true)){ createDetailRow("Transports",sea.transports?.description ?? "", true) if (sea.qty > 0){createDetailRow("Quantity",sea.qty.description) } } if (sea.dive > 0) {createDetailRow("Maximum Depth",sea.dive.description+" meters", true)} createDetailRow("Speed",sea.speed.description+" kph", true) createDetailRow("Autonomy",sea.auto.description+" km", true) createDetailRow("Displacement",sea.tonnage.description+" tons", true) } func setDetailViews(air: Air){ if let it = air.gun{ createDetailRow("Cannon",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} if (it.penetration > 0){createDetailRow("Penetration",it.penetration.description+"mm") } } if let it = air.agm{ createDetailRow("Air-to-Ground Missile",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} createDetailRow("Penetration",it.penetration.description+"mm") } if let it = air.asm { createDetailRow("Air-to-Surface Missile",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} } if let it = air.aam { createDetailRow("Air-to-Air Missile",it.name ?? "", true) if (it.range > 0 ) {createDetailRow("Range",it.range.description+" meters")} } createDetailRow("Speed",air.speed.description+" kph", true) createDetailRow("Ceiling",air.ceiling.description+" meters", true) createDetailRow("Autonomy",air.auto.description+" km", true) createDetailRow("Weight",air.weight.description+" kg", true) } // MARK: - Buttons @IBAction func closeButtonPressed(_ sender: Any) { self.dismiss(animated: true, completion: nil) } }
mit
9d75f90a9b1d057b041260b7c0bc42a9
50.186047
151
0.637551
4.194378
false
false
false
false
chenzhe555/core-ios-swift
core-ios-swift/AppDelegate.swift
1
5522
// // AppDelegate.swift // core-ios-swift // // Created by 陈哲#[email protected] on 16/2/17. // Copyright © 2016年 陈哲是个好孩子. All rights reserved. // import UIKit import Alamofire typealias funcBlock = () -> String @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, BaseHttpServiceDelegate_s { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let dic1: NSMutableDictionary = ["key1":"1111","key2":"2222","key1":"333","key6": ["key1":"66","key2": "xxxx"]]; let dic2: NSMutableDictionary = ["key1":"1111","key2":"2222","key1":"333","key6": ["key1":"66","key2": "xxxx"]]; // BaseHttpEncryption.encrytionParameterMethod1(dic1, andKeyArray: MCHttpEncryption.setParametersArray()); do{ try BaseHttpEncryption_s.encrytionParameterMethod1(dic2, keyArray: MCHttpEncryption_s.setParametersArray()); } catch BaseHttpErrorType_s.NotOverrideMethod_setParamater { print("------------------"); } catch { } // Alamofire.request(.GET, "http://www.test.com").responseJSON { (response) -> Void in // print("回来了呢\(response.result)"); // }; // // // // // Alamofire.request(.GET, "http://localhost/launchadconfig/getimg", parameters: ["account": "chenzhe","password": "111"], encoding: .URL, headers: ["Content-Type": "application/json"]).responseJSON { (response) -> Void in // print(response.result); // }; // Alamofire.request(.GET, "http://localhost/launchadconfig/getimg").responseJSON { (response) -> Void in // print(response.result.value); // }"core-ios-swift/Framework_swift/Service/*.{h,swift}" // MCLog("陈哲是个好孩子"); let service = MCHttpService(); service.delegate = self; // service.login("chenzhe", password: "111", requsetObj: HttpAppendParamaters_s.init(needToken: true, alertType: MCHttpAlertType_s.MCHttpAlertTypeNone_s)); service.login("chenzhe", password: "111", condition: BaseHttpAppendCondition_s()); let v1: UIViewController = ViewController(); let v2: UIViewController = ViewController(); let v3: UIViewController = ViewController(); let v4: UIViewController = ViewController(); let nav1: UINavigationController = UINavigationController(rootViewController: v1); let nav2: UINavigationController = UINavigationController(rootViewController: v2); let nav3: UINavigationController = UINavigationController(rootViewController: v3); let nav4: UINavigationController = UINavigationController(rootViewController: v4); let tabbar: BaseTabbar_s = BaseTabbar_s(); tabbar.setDataArray(["1111","2222","333","4"], normalArray: [UIImage(named: "icon_my_normal")!,UIImage(named: "icon_allGoods_normal")!,UIImage(named: "icon_home_normal")!,UIImage(named: "icon_shopCart_normal")!], selectedArray: [UIImage(named: "icon_my_selected")!,UIImage(named: "icon_allGoods_selected")!,UIImage(named: "icon_home_selected")!,UIImage(named: "icon_shopCart_selected")!]); tabbar.viewControllers = [nav1,nav2,nav3,nav4]; tabbar.createTabbar(); self.window?.rootViewController = tabbar; return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func requesetSuccess(response: BaseHttpResponse_s) { print("打印出来是---\(response.object)"); } func requestFail(response: BaseHttpResponse_s) { print("失败打印出来是---\(response.object)"); } }
mit
c870c92416a7c5e46cefac10cbbfff2a
46.025862
397
0.672411
4.523217
false
false
false
false
corosukeK/ConstraintsTranslator
Sources/View.swift
1
1415
// // View.swift // ConstraintsTranslator // // Created by akuraru on 2017/03/04. // // import Foundation import AEXML struct View { let id: String let subviews: [View] let constraints: [Constraint] let userLabel: String? init(element: AEXMLElement) { self.id = element.attributes["id"]! self.userLabel = element.attributes["userLabel"] let subviewsElement = element["subviews"].children self.subviews = subviewsElement.map{ (element) -> View in return View(element: element) } let constraintsElement = element["constraints"]["constraint"] if constraintsElement.error == nil { self.constraints = constraintsElement.all!.map({ (element) -> Constraint in return Constraint(element: element) }) } else { self.constraints = [] } } init(id: String, subviews: [View], constraints: [Constraint], userLabel: String? = nil) { self.id = id self.subviews = subviews self.constraints = constraints self.userLabel = userLabel } } extension View: Equatable { public static func ==(lhs: View, rhs: View) -> Bool { return lhs.id == rhs.id && arrayEqual(lhs: lhs.subviews, rhs: rhs.subviews) && arrayEqual(lhs: lhs.constraints, rhs: rhs.constraints) } }
apache-2.0
6b8587a07258bf1224bc618e4fb3199a
26.745098
93
0.588693
4.4081
false
false
false
false
JakeLin/IBAnimatable
IBAnimatableApp/IBAnimatableApp/Playground/UserInterfaces/Gradients/GradientCustomStartPointViewController.swift
2
2766
// // GradientCustomStartPointViewController.swift // IBAnimatable // // Created by Tom Baranes on 22/12/2016. // Copyright © 2016 IBAnimatable. All rights reserved. // import UIKit import IBAnimatable final class GradientCustomStartPointViewController: UIViewController, GradientModePresenter { @IBOutlet fileprivate weak var gView: AnimatableView! var gradientMode: GradientMode = .linear let gradientValues = ParamType(fromEnum: GradientType.self) let coordPointValues = ParamType.number(min: 0, max: 1, interval: 0.1, ascending: true, unit: "") lazy var componentValues: [ParamType] = [self.gradientValues, self.coordPointValues, self.coordPointValues, self.coordPointValues, self.coordPointValues] override func viewDidLoad() { super.viewDidLoad() gView.gradientMode = gradientMode gView.predefinedGradient = GradientType(rawValue: gradientValues.value(at: 0)) } } extension GradientCustomStartPointViewController: UIPickerViewDelegate, UIPickerViewDataSource { func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return componentValues[component].count() } func numberOfComponents(in pickerView: UIPickerView) -> Int { return componentValues.count } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { let label = UILabel() label.textColor = .white label.textAlignment = .center label.minimumScaleFactor = 0.5 label.text = componentValues[component].title(at: row) return label } func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { return componentValues[component].title(at: row).colorize(.white) } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let startX = pickerView.selectedRow(inComponent: 1) let startY = pickerView.selectedRow(inComponent: 2) let endX = pickerView.selectedRow(inComponent: 3) let endY = pickerView.selectedRow(inComponent: 4) let startPoint = CGPoint(x: Double(coordPointValues.value(at: startX)) ?? 0, y: Double(coordPointValues.value(at: startY)) ?? 0) let endPoint = CGPoint(x: Double(coordPointValues.value(at: endX)) ?? 0, y: Double(coordPointValues.value(at: endY)) ?? 0) gView.startPoint = .custom(start: startPoint, end: endPoint) gView.predefinedGradient = GradientType(rawValue: gradientValues.value(at: pickerView.selectedRow(inComponent: 0))) gView.configureGradient() } }
mit
0ca2e523b55a8c8ef12ec4f335a6232b
42.203125
132
0.707052
4.608333
false
false
false
false
kylecrawshaw/ImagrAdmin
ImagrAdmin/WorkflowSupport/WorkflowComponents/EraseVolumeComponent/EraseVolumeComponent.swift
1
1242
// // ImageComponent.swift // ImagrManager // // Created by Kyle Crawshaw on 7/12/16. // Copyright © 2016 Kyle Crawshaw. All rights reserved. // import Foundation import Cocoa class EraseVolumeComponent: BaseComponent { var volumeName: String! var volumeFormat: String! init(id: Int!, workflowName: String!, workflowId: Int!) { super.init(id: id, type: "eraseVolume", workflowName: workflowName, workflowId: workflowId) super.componentViewController = EraseVolumeViewController() self.volumeName = "" self.volumeFormat = "Journaled HFS+" } init(id: Int!, workflowName: String!, workflowId: Int!, dict: NSDictionary!) { super.init(id: id, type: "eraseVolume", workflowName: workflowName, workflowId: workflowId) super.componentViewController = EraseVolumeViewController() self.volumeName = dict.valueForKey("name") as? String ?? "" self.volumeFormat = dict.valueForKey("format") as? String ?? "Journaled HFS+" } override func asDict() -> NSDictionary? { let dict: [String: AnyObject] = [ "type": type, "name": volumeName, "format": volumeFormat ] return dict } }
apache-2.0
058ffdba6683f53c993039deca862b9b
29.292683
99
0.639807
4.221088
false
false
false
false
m-alani/contests
leetcode/removeElement.swift
1
587
// // removeElement.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/remove-element/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // class Solution { func removeElement(_ nums: inout [Int], _ val: Int) -> Int { var last = nums.count, itr = 0 while (itr < last) { if (nums[itr] == val) { last -= 1 nums[itr] = nums[last] } else { itr += 1 } } return last } }
mit
437233f0afe5d09034dfbf40e5960e24
24.521739
117
0.591141
3.452941
false
false
false
false
bitjammer/swift
test/SILGen/vtable_thunks.swift
1
12957
// RUN: %target-swift-frontend -sdk %S/Inputs -emit-silgen -I %S/Inputs -enable-source-import %s -disable-objc-attr-requires-foundation-module | %FileCheck %s protocol AddrOnly {} func callMethodsOnD<U>(d: D, b: B, a: AddrOnly, u: U, i: Int) { _ = d.iuo(x: b, y: b, z: b) _ = d.f(x: b, y: b) _ = d.f2(x: b, y: b) _ = d.f3(x: b, y: b) _ = d.f4(x: b, y: b) _ = d.g(x: a, y: a) _ = d.g2(x: a, y: a) _ = d.g3(x: a, y: a) _ = d.g4(x: a, y: a) _ = d.h(x: u, y: u) _ = d.h2(x: u, y: u) _ = d.h3(x: u, y: u) _ = d.h4(x: u, y: u) _ = d.i(x: i, y: i) _ = d.i2(x: i, y: i) _ = d.i3(x: i, y: i) _ = d.i4(x: i, y: i) } func callMethodsOnF<U>(d: F, b: B, a: AddrOnly, u: U, i: Int) { _ = d.iuo(x: b, y: b, z: b) _ = d.f(x: b, y: b) _ = d.f2(x: b, y: b) _ = d.f3(x: b, y: b) _ = d.f4(x: b, y: b) _ = d.g(x: a, y: a) _ = d.g2(x: a, y: a) _ = d.g3(x: a, y: a) _ = d.g4(x: a, y: a) _ = d.h(x: u, y: u) _ = d.h2(x: u, y: u) _ = d.h3(x: u, y: u) _ = d.h4(x: u, y: u) _ = d.i(x: i, y: i) _ = d.i2(x: i, y: i) _ = d.i3(x: i, y: i) _ = d.i4(x: i, y: i) } @objc class B { // We only allow B! -> B overrides for @objc methods. // The IUO force-unwrap requires a thunk. @objc func iuo(x: B, y: B!, z: B) -> B? {} // f* don't require thunks, since the parameters and returns are object // references. func f(x: B, y: B) -> B? {} func f2(x: B, y: B) -> B? {} func f3(x: B, y: B) -> B {} func f4(x: B, y: B) -> B {} // Thunking monomorphic address-only params and returns func g(x: AddrOnly, y: AddrOnly) -> AddrOnly? {} func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly? {} func g3(x: AddrOnly, y: AddrOnly) -> AddrOnly {} func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} // Thunking polymorphic address-only params and returns func h<T>(x: T, y: T) -> T? {} func h2<T>(x: T, y: T) -> T? {} func h3<T>(x: T, y: T) -> T {} func h4<T>(x: T, y: T) -> T {} // Thunking value params and returns func i(x: Int, y: Int) -> Int? {} func i2(x: Int, y: Int) -> Int? {} func i3(x: Int, y: Int) -> Int {} func i4(x: Int, y: Int) -> Int {} // Note: i3, i4 are implicitly @objc } class D: B { override func iuo(x: B?, y: B, z: B) -> B {} override func f(x: B?, y: B) -> B {} override func f2(x: B, y: B) -> B {} override func f3(x: B?, y: B) -> B {} override func f4(x: B, y: B) -> B {} override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func h<U>(x: U?, y: U) -> U {} override func h2<U>(x: U, y: U) -> U {} override func h3<U>(x: U?, y: U) -> U {} override func h4<U>(x: U, y: U) -> U {} override func i(x: Int?, y: Int) -> Int {} override func i2(x: Int, y: Int) -> Int {} // Int? cannot be represented in ObjC so the override has to be // explicitly @nonobjc @nonobjc override func i3(x: Int?, y: Int) -> Int {} override func i4(x: Int, y: Int) -> Int {} } // Inherits the thunked impls from D class E: D { } // Overrides w/ its own thunked impls class F: D { override func f(x: B?, y: B) -> B {} override func f2(x: B, y: B) -> B {} override func f3(x: B?, y: B) -> B {} override func f4(x: B, y: B) -> B {} override func g(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g2(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func g3(x: AddrOnly?, y: AddrOnly) -> AddrOnly {} override func g4(x: AddrOnly, y: AddrOnly) -> AddrOnly {} override func h<U>(x: U?, y: U) -> U {} override func h2<U>(x: U, y: U) -> U {} override func h3<U>(x: U?, y: U) -> U {} override func h4<U>(x: U, y: U) -> U {} override func i(x: Int?, y: Int) -> Int {} override func i2(x: Int, y: Int) -> Int {} // Int? cannot be represented in ObjC so the override has to be // explicitly @nonobjc @nonobjc override func i3(x: Int?, y: Int) -> Int {} override func i4(x: Int, y: Int) -> Int {} } // This test is incorrect in semantic SIL today. But it will be fixed in // forthcoming commits. // // CHECK-LABEL: sil private @_T013vtable_thunks1DC3iuo{{[_0-9a-zA-Z]*}}FTV // CHECK: bb0([[X:%.*]] : $B, [[Y:%.*]] : $Optional<B>, [[Z:%.*]] : $B, [[W:%.*]] : $D): // CHECK: [[WRAP_X:%.*]] = enum $Optional<B>, #Optional.some!enumelt.1, [[X]] : $B // CHECK: switch_enum [[Y]] : $Optional<B>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[NONE_BB]]: // CHECK: [[DIAGNOSE_UNREACHABLE_FUNC:%.*]] = function_ref @_T0s30_diagnoseUnexpectedNilOptional{{.*}} // CHECK: apply [[DIAGNOSE_UNREACHABLE_FUNC]] // CHECK: unreachable // CHECK: [[SOME_BB]]([[UNWRAP_Y:%.*]] : $B): // CHECK: [[THUNK_FUNC:%.*]] = function_ref @_T013vtable_thunks1DC3iuo{{.*}} // CHECK: [[RES:%.*]] = apply [[THUNK_FUNC]]([[WRAP_X]], [[UNWRAP_Y]], [[Z]], [[W]]) // CHECK: [[WRAP_RES:%.*]] = enum $Optional<B>, {{.*}} [[RES]] // CHECK: return [[WRAP_RES]] // CHECK-LABEL: sil private @_T013vtable_thunks1DC1g{{[_0-9a-zA-Z]*}}FTV // TODO: extra copies here // CHECK: [[WRAPPED_X_ADDR:%.*]] = init_enum_data_addr [[WRAP_X_ADDR:%.*]] : // CHECK: copy_addr [take] {{%.*}} to [initialization] [[WRAPPED_X_ADDR]] // CHECK: inject_enum_addr [[WRAP_X_ADDR]] // CHECK: [[RES_ADDR:%.*]] = alloc_stack // CHECK: apply {{%.*}}([[RES_ADDR]], [[WRAP_X_ADDR]], %2, %3) // CHECK: [[DEST_ADDR:%.*]] = init_enum_data_addr %0 // CHECK: copy_addr [take] [[RES_ADDR]] to [initialization] [[DEST_ADDR]] // CHECK: inject_enum_addr %0 class ThrowVariance { func mightThrow() throws {} } class NoThrowVariance: ThrowVariance { override func mightThrow() {} } // rdar://problem/20657811 class X<T: B> { func foo(x: T) { } } class Y: X<D> { override func foo(x: D) { } } // rdar://problem/21154055 // Ensure reabstraction happens when necessary to get a value in or out of an // optional. class Foo { func foo(x: @escaping (Int) -> Int) -> ((Int) -> Int)? {} } class Bar: Foo { override func foo(x: ((Int) -> Int)?) -> (Int) -> Int {} } // rdar://problem/21364764 // Ensure we can override an optional with an IUO or vice-versa. struct S {} class Aap { func cat(b: B?) -> B? {} func dog(b: B!) -> B! {} func catFast(s: S?) -> S? {} func dogFast(s: S!) -> S! {} func flip() -> (() -> S?) {} func map() -> (S) -> () -> Aap? {} } class Noot : Aap { override func cat(b: B!) -> B! {} override func dog(b: B?) -> B? {} override func catFast(s: S!) -> S! {} override func dogFast(s: S?) -> S? {} override func flip() -> (() -> S) {} override func map() -> (S?) -> () -> Noot {} } // CHECK-LABEL: sil private @_T013vtable_thunks3BarC3foo{{[_0-9a-zA-Z]*}}FTV : $@convention(method) (@owned @callee_owned (Int) -> Int, @guaranteed Bar) -> @owned Optional<@callee_owned (Int) -> Int> // CHECK: [[IMPL:%.*]] = function_ref @_T013vtable_thunks3BarC3foo{{[_0-9a-zA-Z]*}}F // CHECK: apply [[IMPL]] // CHECK-LABEL: sil private @_T013vtable_thunks4NootC4flip{{[_0-9a-zA-Z]*}}FTV // CHECK: [[IMPL:%.*]] = function_ref @_T013vtable_thunks4NootC4flip{{[_0-9a-zA-Z]*}}F // CHECK: [[INNER:%.*]] = apply %1(%0) // CHECK: [[THUNK:%.*]] = function_ref @_T013vtable_thunks1SVIxd_ACSgIxd_TR // CHECK: [[OUTER:%.*]] = partial_apply [[THUNK]]([[INNER]]) // CHECK: return [[OUTER]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T013vtable_thunks1SVIxd_ACSgIxd_TR // CHECK: [[INNER:%.*]] = apply %0() // CHECK: [[OUTER:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, %1 : $S // CHECK: return [[OUTER]] : $Optional<S> // CHECK-LABEL: sil private @_T013vtable_thunks4NootC3map{{[_0-9a-zA-Z]*}}FTV // CHECK: [[IMPL:%.*]] = function_ref @_T013vtable_thunks4NootC3map{{[_0-9a-zA-Z]*}}F // CHECK: [[INNER:%.*]] = apply %1(%0) // CHECK: [[THUNK:%.*]] = function_ref @_T013vtable_thunks1SVSgAA4NootCIxo_Ixyo_AcA3AapCSgIxo_Ixyo_TR // CHECK: [[OUTER:%.*]] = partial_apply [[THUNK]]([[INNER]]) // CHECK: return [[OUTER]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T013vtable_thunks1SVSgAA4NootCIxo_Ixyo_AcA3AapCSgIxo_Ixyo_TR // CHECK: [[ARG:%.*]] = enum $Optional<S>, #Optional.some!enumelt.1, %0 // CHECK: [[INNER:%.*]] = apply %1(%2) // CHECK: [[OUTER:%.*]] = convert_function [[INNER]] : $@callee_owned () -> @owned Noot to $@callee_owned () -> @owned Optional<Aap> // CHECK: return [[OUTER]] // CHECK-LABEL: sil_vtable D { // CHECK: #B.iuo!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable E { // CHECK: #B.iuo!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable F { // CHECK: #B.iuo!1: {{.*}} : hidden _T013vtable_thunks1D{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.f!1: {{.*}} : _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f2!1: {{.*}} : _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f3!1: {{.*}} : _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.f4!1: {{.*}} : _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.g!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g2!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g3!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.g4!1: {{.*}} : _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.h!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h2!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h3!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.h4!1: {{.*}} : _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK: #B.i!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i2!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i3!1: {{.*}} : hidden _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}FTV // CHECK: #B.i4!1: {{.*}} : _T013vtable_thunks1F{{[A-Z0-9a-z_]*}}F // CHECK-LABEL: sil_vtable NoThrowVariance { // CHECK: #ThrowVariance.mightThrow!1: {{.*}} : _T013vtable_thunks{{[A-Z0-9a-z_]*}}F
apache-2.0
99d9f4ce248761d17b1eb6bf28dad938
41.343137
199
0.525585
2.521798
false
false
false
false
juheon0615/HandongSwift2
HandongAppSwift/CVCalendar/CVCalendarWeekView.swift
11
7512
// // CVCalendarWeekView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit class CVCalendarWeekView: UIView { // MARK: - Non public properties private var interactiveView: UIView! override var frame: CGRect { didSet { if let calendarView = calendarView { if calendarView.calendarMode == CalendarMode.WeekView { updateInteractiveView() } } } } private var touchController: CVCalendarTouchController { return calendarView.touchController } // MARK: - Public properties weak var monthView: CVCalendarMonthView! var dayViews: [CVCalendarDayView]! var index: Int! var weekdaysIn: [Int : [Int]]? var weekdaysOut: [Int : [Int]]? var utilizable = false /// Recovery service. weak var calendarView: CVCalendarView! { get { var calendarView: CVCalendarView! if let monthView = monthView, let activeCalendarView = monthView.calendarView { calendarView = activeCalendarView } return calendarView } } // MARK: - Initialization init(monthView: CVCalendarMonthView, index: Int) { self.monthView = monthView self.index = index if let size = monthView.calendarView.weekViewSize { super.init(frame: CGRectMake(0, CGFloat(index) * size.height, size.width, size.height)) } else { super.init(frame: CGRectZero) } // Get weekdays in. let weeksIn = self.monthView!.weeksIn! self.weekdaysIn = weeksIn[self.index!] // Get weekdays out. if let weeksOut = self.monthView!.weeksOut { if self.weekdaysIn?.count < 7 { if weeksOut.count > 1 { let daysOut = 7 - self.weekdaysIn!.count var result: [Int : [Int]]? for weekdaysOut in weeksOut { if weekdaysOut.count == daysOut { let manager = calendarView.manager let key = weekdaysOut.keys.first! let value = weekdaysOut[key]![0] if value > 20 { if self.index == 0 { result = weekdaysOut break } } else if value < 10 { if self.index == manager.monthDateRange(self.monthView!.date!).countOfWeeks - 1 { result = weekdaysOut break } } } } self.weekdaysOut = result! } else { self.weekdaysOut = weeksOut[0] } } } self.createDayViews() } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func mapDayViews(body: (DayView) -> ()) { if let dayViews = dayViews { for dayView in dayViews { body(dayView) } } } } // MARK: - Interactive view setup & management extension CVCalendarWeekView { func updateInteractiveView() { safeExecuteBlock({ let mode = self.monthView!.calendarView!.calendarMode! if mode == .WeekView { if let interactiveView = self.interactiveView { interactiveView.frame = self.bounds interactiveView.removeFromSuperview() self.addSubview(interactiveView) } else { self.interactiveView = UIView(frame: self.bounds) self.interactiveView.backgroundColor = .clearColor() let tapRecognizer = UITapGestureRecognizer(target: self, action: "didTouchInteractiveView:") let pressRecognizer = UILongPressGestureRecognizer(target: self, action: "didPressInteractiveView:") pressRecognizer.minimumPressDuration = 0.3 self.interactiveView.addGestureRecognizer(pressRecognizer) self.interactiveView.addGestureRecognizer(tapRecognizer) self.addSubview(self.interactiveView) } } }, collapsingOnNil: false, withObjects: monthView, monthView?.calendarView) } func didPressInteractiveView(recognizer: UILongPressGestureRecognizer) { let location = recognizer.locationInView(self.interactiveView) let state: UIGestureRecognizerState = recognizer.state switch state { case .Began: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Started)) case .Changed: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Changed)) case .Ended: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Ended)) default: break } } func didTouchInteractiveView(recognizer: UITapGestureRecognizer) { let location = recognizer.locationInView(self.interactiveView) touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Single) } } // MARK: - Content fill & reload extension CVCalendarWeekView { func createDayViews() { dayViews = [CVCalendarDayView]() for i in 1...7 { let dayView = CVCalendarDayView(weekView: self, weekdayIndex: i) safeExecuteBlock({ self.dayViews!.append(dayView) }, collapsingOnNil: true, withObjects: dayViews) addSubview(dayView) } } func reloadDayViews() { if let size = calendarView.dayViewSize, let dayViews = dayViews { let hSpace = calendarView.appearance.spaceBetweenDayViews! for (index, dayView) in enumerate(dayViews) { let hSpace = calendarView.appearance.spaceBetweenDayViews! let x = CGFloat(index) * CGFloat(size.width + hSpace) + hSpace/2 dayView.frame = CGRectMake(x, 0, size.width, size.height) dayView.reloadContent() } } } } // MARK: - Safe execution extension CVCalendarWeekView { func safeExecuteBlock(block: Void -> Void, collapsingOnNil collapsing: Bool, withObjects objects: AnyObject?...) { for object in objects { if object == nil { if collapsing { fatalError("Object { \(object) } must not be nil!") } else { return } } } block() } }
mit
8bc683c80d9db8e7c11d5c6ca5a9377e
32.690583
120
0.523695
6.0096
false
false
false
false
xhjkl/rayban
Rayban/Filewatch.swift
1
1485
// // File modification responder // import Dispatch // Responder to FS events // public class Filewatch { private var handlers: Array<() -> ()> = [] private var eventSource: DispatchSourceFileSystemObject! = nil private var fd: Int32! = nil // True iff notifications shall work with current target // public var working: Bool { return fd != nil } public init() { } // Set target immediately after initialization // public convenience init(path: String) { self.init() self.setTarget(path: path) } // Decide how to respond to FS events // public func addHandler(_ handler: @escaping () -> ()) { handlers.append(handler) } // Decide what file to look to // // While being watched, the file is identified by its descriptor. // Note that if the file was moved, // its path might change, whereas the descriptor shall stay the same. // public func setTarget(path: String) { if fd != nil { close(fd) } path.withCString { [unowned self] bytes in self.fd = open(bytes, O_RDONLY) if self.fd == -1 { self.fd = nil } } if fd == nil { return } eventSource = DispatchSource.makeFileSystemObjectSource(fileDescriptor: fd, eventMask: [.all]) eventSource.setEventHandler { [weak self] in guard self != nil else { return } self!.handlers.forEach { $0() } } eventSource.resume() } deinit { if fd != nil { close(fd) } } }
mit
7d43ef0931571e3eacad2af8f5c7661d
19.342466
98
0.619529
4.068493
false
false
false
false
safarafa/eld_hackaton2405
iOSBookTheHotelRoomApp/iOSBookTheHotelRoomApp/Source/SessionDelegate.swift
11
35351
// // SessionDelegate.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// Responsible for handling all delegate callbacks for the underlying session. open class SessionDelegate: NSObject { // MARK: URLSessionDelegate Overrides /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? // MARK: URLSessionTaskDelegate Overrides /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and /// requires the caller to call the `completionHandler`. open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and /// requires the caller to call the `completionHandler`. open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and /// requires the caller to call the `completionHandler`. open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? // MARK: URLSessionDataDelegate Overrides /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and /// requires caller to call the `completionHandler`. open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and /// requires caller to call the `completionHandler`. open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? // MARK: URLSessionDownloadDelegate Overrides /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: URLSessionStreamDelegate Overrides #if !os(watchOS) /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskReadClosed = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskWriteClosed = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { get { return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void } set { _streamTaskBetterRouteDiscovered = newValue } } /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { get { return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void } set { _streamTaskDidBecomeInputStream = newValue } } var _streamTaskReadClosed: Any? var _streamTaskWriteClosed: Any? var _streamTaskBetterRouteDiscovered: Any? var _streamTaskDidBecomeInputStream: Any? #endif // MARK: Properties var retrier: RequestRetrier? weak var sessionManager: SessionManager? private var requests: [Int: Request] = [:] private let lock = NSLock() /// Access the task delegate for the specified task in a thread-safe manner. open subscript(task: URLSessionTask) -> Request? { get { lock.lock() ; defer { lock.unlock() } return requests[task.taskIdentifier] } set { lock.lock() ; defer { lock.unlock() } requests[task.taskIdentifier] = newValue } } // MARK: Lifecycle /// Initializes the `SessionDelegate` instance. /// /// - returns: The new `SessionDelegate` instance. public override init() { super.init() } // MARK: NSObject Overrides /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond /// to a specified message. /// /// - parameter selector: A selector that identifies a message. /// /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. open override func responds(to selector: Selector) -> Bool { #if !os(macOS) if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { return sessionDidFinishEventsForBackgroundURLSession != nil } #endif #if !os(watchOS) if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { switch selector { case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): return streamTaskReadClosed != nil case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): return streamTaskWriteClosed != nil case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): return streamTaskBetterRouteDiscovered != nil case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): return streamTaskDidBecomeInputAndOutputStreams != nil default: break } } #endif switch selector { case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): return sessionDidBecomeInvalidWithError != nil case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) default: return type(of: self).instancesRespond(to: selector) } } } // MARK: - URLSessionDelegate extension SessionDelegate: URLSessionDelegate { /// Tells the delegate that the session has been invalidated. /// /// - parameter session: The session object that was invalidated. /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { sessionDidBecomeInvalidWithError?(session, error) } /// Requests credentials from the delegate in response to a session-level authentication request from the /// remote server. /// /// - parameter session: The session containing the task that requested authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard sessionDidReceiveChallengeWithCompletion == nil else { sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) return } var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling var credential: URLCredential? if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), let serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluate(serverTrust, forHost: host) { disposition = .useCredential credential = URLCredential(trust: serverTrust) } else { disposition = .cancelAuthenticationChallenge } } } completionHandler(disposition, credential) } #if !os(macOS) /// Tells the delegate that all messages enqueued for a session have been delivered. /// /// - parameter session: The session that no longer has any outstanding requests. open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { sessionDidFinishEventsForBackgroundURLSession?(session) } #endif } // MARK: - URLSessionTaskDelegate extension SessionDelegate: URLSessionTaskDelegate { /// Tells the delegate that the remote server requested an HTTP redirect. /// /// - parameter session: The session containing the task whose request resulted in a redirect. /// - parameter task: The task whose request resulted in a redirect. /// - parameter response: An object containing the server’s response to the original request. /// - parameter request: A URL request object filled out with the new location. /// - parameter completionHandler: A closure that your handler should call with either the value of the request /// parameter, a modified URL request object, or NULL to refuse the redirect and /// return the body of the redirect response. open func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { guard taskWillPerformHTTPRedirectionWithCompletion == nil else { taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) return } var redirectRequest: URLRequest? = request if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } /// Requests credentials from the delegate in response to an authentication request from the remote server. /// /// - parameter session: The session containing the task whose request requires authentication. /// - parameter task: The task whose request requires authentication. /// - parameter challenge: An object that contains the request for authentication. /// - parameter completionHandler: A handler that your delegate method must call providing the disposition /// and credential. open func urlSession( _ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { guard taskDidReceiveChallengeWithCompletion == nil else { taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) return } if let taskDidReceiveChallenge = taskDidReceiveChallenge { let result = taskDidReceiveChallenge(session, task, challenge) completionHandler(result.0, result.1) } else if let delegate = self[task]?.delegate { delegate.urlSession( session, task: task, didReceive: challenge, completionHandler: completionHandler ) } else { urlSession(session, didReceive: challenge, completionHandler: completionHandler) } } /// Tells the delegate when a task requires a new request body stream to send to the remote server. /// /// - parameter session: The session containing the task that needs a new body stream. /// - parameter task: The task that needs a new body stream. /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. open func urlSession( _ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { guard taskNeedNewBodyStreamWithCompletion == nil else { taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) return } if let taskNeedNewBodyStream = taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task]?.delegate { delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) } } /// Periodically informs the delegate of the progress of sending body content to the server. /// /// - parameter session: The session containing the data task. /// - parameter task: The data task. /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. /// - parameter totalBytesSent: The total number of bytes sent so far. /// - parameter totalBytesExpectedToSend: The expected length of the body data. open func urlSession( _ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { delegate.URLSession( session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend ) } } #if !os(watchOS) /// Tells the delegate that the session finished collecting metrics for the task. /// /// - parameter session: The session collecting the metrics. /// - parameter task: The task whose metrics have been collected. /// - parameter metrics: The collected metrics. @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) @objc(URLSession:task:didFinishCollectingMetrics:) open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { self[task]?.delegate.metrics = metrics } #endif /// Tells the delegate that the task finished transferring data. /// /// - parameter session: The session containing the task whose request finished transferring data. /// - parameter task: The task whose request finished transferring data. /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { /// Executed after it is determined that the request is not going to be retried let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in guard let strongSelf = self else { return } strongSelf.taskDidComplete?(session, task, error) strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) NotificationCenter.default.post( name: Notification.Name.Task.DidComplete, object: strongSelf, userInfo: [Notification.Key.Task: task] ) strongSelf[task] = nil } guard let request = self[task], let sessionManager = sessionManager else { completeTask(session, task, error) return } // Run all validations on the request before checking if an error occurred request.validations.forEach { $0() } // Determine whether an error has occurred var error: Error? = error if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil { error = taskDelegate.error } /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request /// should be retried. Otherwise, complete the task by notifying the task delegate. if let retrier = retrier, let error = error { retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in guard shouldRetry else { completeTask(session, task, error) ; return } DispatchQueue.utility.after(timeDelay) { [weak self] in guard let strongSelf = self else { return } let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false if retrySucceeded, let task = request.task { strongSelf[task] = request return } else { completeTask(session, task, error) } } } } else { completeTask(session, task, error) } } } // MARK: - URLSessionDataDelegate extension SessionDelegate: URLSessionDataDelegate { /// Tells the delegate that the data task received the initial reply (headers) from the server. /// /// - parameter session: The session containing the data task that received an initial reply. /// - parameter dataTask: The data task that received an initial reply. /// - parameter response: A URL response object populated with headers. /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a /// constant to indicate whether the transfer should continue as a data task or /// should become a download task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { guard dataTaskDidReceiveResponseWithCompletion == nil else { dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) return } var disposition: URLSession.ResponseDisposition = .allow if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } /// Tells the delegate that the data task was changed to a download task. /// /// - parameter session: The session containing the task that was replaced by a download task. /// - parameter dataTask: The data task that was replaced by a download task. /// - parameter downloadTask: The new download task that replaced the data task. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) } } /// Tells the delegate that the data task has received some of the expected data. /// /// - parameter session: The session containing the data task that provided data. /// - parameter dataTask: The data task that provided data. /// - parameter data: A data object containing the transferred data. open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { if let dataTaskDidReceiveData = dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { delegate.urlSession(session, dataTask: dataTask, didReceive: data) } } /// Asks the delegate whether the data (or upload) task should store the response in the cache. /// /// - parameter session: The session containing the data (or upload) task. /// - parameter dataTask: The data (or upload) task. /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current /// caching policy and the values of certain received headers, such as the Pragma /// and Cache-Control headers. /// - parameter completionHandler: A block that your handler must call, providing either the original proposed /// response, a modified version of that response, or NULL to prevent caching the /// response. If your delegate implements this method, it must call this completion /// handler; otherwise, your app leaks memory. open func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) { guard dataTaskWillCacheResponseWithCompletion == nil else { dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) return } if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { delegate.urlSession( session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler ) } else { completionHandler(proposedResponse) } } } // MARK: - URLSessionDownloadDelegate extension SessionDelegate: URLSessionDownloadDelegate { /// Tells the delegate that a download task has finished downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that finished. /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either /// open the file for reading or move it to a permanent location in your app’s sandbox /// container directory before returning from this delegate method. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) } } /// Periodically informs the delegate about the download’s progress. /// /// - parameter session: The session containing the download task. /// - parameter downloadTask: The download task. /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate /// method was called. /// - parameter totalBytesWritten: The total number of bytes transferred so far. /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length /// header. If this header was not provided, the value is /// `NSURLSessionTransferSizeUnknown`. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite ) } } /// Tells the delegate that the download task has resumed downloading. /// /// - parameter session: The session containing the download task that finished. /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the /// existing content, then this value is zero. Otherwise, this value is an /// integer representing the number of bytes on disk that do not need to be /// retrieved again. /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. open func urlSession( _ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { delegate.urlSession( session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes ) } } } // MARK: - URLSessionStreamDelegate #if !os(watchOS) @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) extension SessionDelegate: URLSessionStreamDelegate { /// Tells the delegate that the read side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { streamTaskReadClosed?(session, streamTask) } /// Tells the delegate that the write side of the connection has been closed. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { streamTaskWriteClosed?(session, streamTask) } /// Tells the delegate that the system has determined that a better route to the host is available. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { streamTaskBetterRouteDiscovered?(session, streamTask) } /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. /// /// - parameter session: The session. /// - parameter streamTask: The stream task. /// - parameter inputStream: The new input stream. /// - parameter outputStream: The new output stream. open func urlSession( _ session: URLSession, streamTask: URLSessionStreamTask, didBecome inputStream: InputStream, outputStream: OutputStream) { streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) } } #endif
mit
7b2768db40da039727f543e77309fa08
48.158554
192
0.675117
6.158738
false
false
false
false
twostraws/SwiftGD
Sources/SwiftGD/Geometry/Point.swift
1
1304
/// A structure that contains a point in a two-dimensional coordinate system. public struct Point { /// The x-coordinate of the point. public var x: Int /// The y-coordinate of the point. public var y: Int /// Creates a point with specified coordinates. /// /// - Parameters: /// - x: The x-coordinate of the point /// - y: The y-coordinate of the point public init(x: Int, y: Int) { self.x = x self.y = y } } extension Point { /// The point at the origin (0,0). public static let zero = Point(x: 0, y: 0) /// Creates a point with specified coordinates. /// /// - Parameters: /// - x: The x-coordinate of the point /// - y: The y-coordinate of the point public init(x: Int32, y: Int32) { self.init(x: Int(x), y: Int(y)) } } extension Point: Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Point, rhs: Point) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } }
mit
72c471403b328ca1fffd9e1a51426c7b
27.347826
77
0.565184
3.612188
false
false
false
false
tdscientist/ShelfView-iOS
Example/Pods/Kingfisher/Sources/Image/Filter.swift
1
5540
// // Filter.swift // Kingfisher // // Created by Wei Wang on 2016/08/31. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreImage // Reuse the same CI Context for all CI drawing. private let ciContext = CIContext(options: nil) /// Represents the type of transformer method, which will be used in to provide a `Filter`. public typealias Transformer = (CIImage) -> CIImage? /// Represents a processor based on a `CIImage` `Filter`. /// It requires a filter to create an `ImageProcessor`. public protocol CIImageProcessor: ImageProcessor { var filter: Filter { get } } extension CIImageProcessor { /// Processes the input `ImageProcessItem` with this processor. /// /// - Parameters: /// - item: Input item which will be processed by `self`. /// - options: Options when processing the item. /// - Returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.apply(filter) case .data: return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// A wrapper struct for a `Transformer` of CIImage filters. A `Filter` /// value could be used to create a `CIImage` processor. public struct Filter { let transform: Transformer public init(transform: @escaping Transformer) { self.transform = transform } /// Tint filter which will apply a tint color to images. public static var tint: (Color) -> Filter = { color in Filter { input in let colorFilter = CIFilter(name: "CIConstantColorGenerator")! colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) let filter = CIFilter(name: "CISourceOverCompositing")! let colorImage = colorFilter.outputImage filter.setValue(colorImage, forKey: kCIInputImageKey) filter.setValue(input, forKey: kCIInputBackgroundImageKey) return filter.outputImage?.cropped(to: input.extent) } } /// Represents color control elements. It is a tuple of /// `(brightness, contrast, saturation, inputEV)` public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) /// Color control filter which will apply color control change to images. public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in let (brightness, contrast, saturation, inputEV) = arg return Filter { input in let paramsColor = [kCIInputBrightnessKey: brightness, kCIInputContrastKey: contrast, kCIInputSaturationKey: saturation] let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor) let paramsExposure = [kCIInputEVKey: inputEV] return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure) } } } extension KingfisherWrapper where Base: Image { /// Applies a `Filter` containing `CIImage` transformer to `self`. /// /// - Parameter filter: The filter used to transform `self`. /// - Returns: A transformed image by input `Filter`. /// /// - Note: /// Only CG-based images are supported. If any error happens /// during transforming, `self` will be returned. public func apply(_ filter: Filter) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Tint image only works for CG-based image.") return base } let inputImage = CIImage(cgImage: cgImage) guard let outputImage = filter.transform(inputImage) else { return base } guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { assertionFailure("[Kingfisher] Can not make an tint image within context.") return base } #if os(macOS) return fixedForRetinaPixel(cgImage: result, to: size) #else return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation) #endif } }
mit
77e0721aabb26256f2d8e5f160011f09
38.014085
97
0.656318
4.821584
false
false
false
false
wantedly/ReactKit
ReactKit/Foundation/NSObject+Own.swift
2
853
// // NSObject+Owner.swift // ReactKit // // Created by Yasuhiro Inami on 2014/11/11. // Copyright (c) 2014年 Yasuhiro Inami. All rights reserved. // import Foundation private var owninigStreamsKey: UInt8 = 0 internal extension NSObject { internal typealias AnyStream = AnyObject // NOTE: can't use Stream<AnyObject?> internal var _owninigStreams: [AnyStream] { get { var owninigStreams = objc_getAssociatedObject(self, &owninigStreamsKey) as? [AnyStream] if owninigStreams == nil { owninigStreams = [] self._owninigStreams = owninigStreams! } return owninigStreams! } set { objc_setAssociatedObject(self, &owninigStreamsKey, newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } } }
mit
a798f2f9868177b05ea6c454d74d1fec
26.483871
131
0.632197
4.052381
false
false
false
false
JohnEstropia/CoreStore
Sources/CoreStoreSchema.swift
1
40578
// // CoreStoreSchema.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import CoreData import Foundation // MARK: - CoreStoreSchema /** The `CoreStoreSchema` describes models written for `CoreStoreObject` Swift class declarations for a particular model version. `CoreStoreObject` entities for a model version should be added to `CoreStoreSchema` instance. ``` class Animal: CoreStoreObject { let species = Value.Required<String>("species", initial: "") let nickname = Value.Optional<String>("nickname") let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let name = Value.Required<String>("name", initial: "") let pet = Relationship.ToOne<Animal>("pet", inverse: { $0.master }) } CoreStoreDefaults.dataStack = DataStack( CoreStoreSchema( modelVersion: "V1", entities: [ Entity<Animal>("Animal"), Entity<Person>("Person") ], versionLock: [ "Animal": [0x2698c812ebbc3b97, 0x751e3fa3f04cf9, 0x51fd460d3babc82, 0x92b4ba735b5a3053], "Person": [0xae4060a59f990ef0, 0x8ac83a6e1411c130, 0xa29fea58e2e38ab6, 0x2071bb7e33d77887] ] ) ) ``` - SeeAlso: CoreStoreObject - SeeAlso: Entity */ public final class CoreStoreSchema: DynamicSchema { /** Initializes a `CoreStoreSchema`. Using this initializer only if the entities don't need to be assigned to particular "Configurations". To use multiple configurations (for example, to separate entities in different `StorageInterface`s), use the `init(modelVersion:entitiesByConfiguration:versionLock:)` initializer. ``` class Animal: CoreStoreObject { let species = Value.Required<String>("species", initial: "") let nickname = Value.Optional<String>("nickname") let master = Relationship.ToOne<Person>("master") } class Person: CoreStoreObject { let name = Value.Required<String>("name", initial: "") let pet = Relationship.ToOne<Animal>("pet", inverse: { $0.master }) } CoreStoreDefaults.dataStack = DataStack( CoreStoreSchema( modelVersion: "V1", entities: [ Entity<Animal>("Animal"), Entity<Person>("Person") ], versionLock: [ "Animal": [0x2698c812ebbc3b97, 0x751e3fa3f04cf9, 0x51fd460d3babc82, 0x92b4ba735b5a3053], "Person": [0xae4060a59f990ef0, 0x8ac83a6e1411c130, 0xa29fea58e2e38ab6, 0x2071bb7e33d77887] ] ) ) ``` - parameter modelVersion: the model version for the schema. This string should be unique from other `DynamicSchema`'s model versions. - parameter entities: an array of `Entity<T>` pertaining to all `CoreStoreObject` subclasses to be added to the schema version. - parameter versionLock: an optional list of `VersionLock` hashes for each entity name in the `entities` array. If any `DynamicEntity` doesn't match its version lock hash, an assertion will be raised. */ public convenience init(modelVersion: ModelVersion, entities: [DynamicEntity], versionLock: VersionLock? = nil) { var entityConfigurations: [DynamicEntity: Set<String>] = [:] for entity in entities { entityConfigurations[entity] = [] } self.init( modelVersion: modelVersion, entityConfigurations: entityConfigurations, versionLock: versionLock ) } /** Initializes a `CoreStoreSchema`. Using this initializer if multiple "Configurations" (for example, to separate entities in different `StorageInterface`s) are needed. To add an entity only to the default configuration, assign an empty set to its configurations list. Note that regardless of the set configurations, all entities will be added to the default configuration. ``` class Animal: CoreStoreObject { let species = Value.Required<String>("species", initial: "") let nickname = Value.Optional<String>("nickname") } class Person: CoreStoreObject { let name = Value.Required<String>("name", initial: "") } CoreStoreDefaults.dataStack = DataStack( CoreStoreSchema( modelVersion: "V1", entityConfigurations: [ Entity<Animal>("Animal"): [], Entity<Person>("Person"): ["People"] ], versionLock: [ "Animal": [0x2698c812ebbc3b97, 0x751e3fa3f04cf9, 0x51fd460d3babc82, 0x92b4ba735b5a3053], "Person": [0xae4060a59f990ef0, 0x8ac83a6e1411c130, 0xa29fea58e2e38ab6, 0x2071bb7e33d77887] ] ) ) ``` - parameter modelVersion: the model version for the schema. This string should be unique from other `DynamicSchema`'s model versions. - parameter entityConfigurations: a dictionary with `Entity<T>` pertaining to all `CoreStoreObject` subclasses and the corresponding list of "Configurations" they should be added to. To add an entity only to the default configuration, assign an empty set to its configurations list. Note that regardless of the set configurations, all entities will be added to the default configuration. - parameter versionLock: an optional list of `VersionLock` hashes for each entity name in the `entities` array. If any `DynamicEntity` doesn't match its version lock hash, an assertion will be raised. */ public required init(modelVersion: ModelVersion, entityConfigurations: [DynamicEntity: Set<String>], versionLock: VersionLock? = nil) { var actualEntitiesByConfiguration: [String: Set<DynamicEntity>] = [:] for (entity, configurations) in entityConfigurations { for configuration in configurations { var entities: Set<DynamicEntity> if let existingEntities = actualEntitiesByConfiguration[configuration] { entities = existingEntities } else { entities = [] } entities.insert(entity) actualEntitiesByConfiguration[configuration] = entities } } let allEntities = Set(entityConfigurations.keys) actualEntitiesByConfiguration[DataStack.defaultConfigurationName] = allEntities Internals.assert( Internals.with { let expectedCount = allEntities.count return Set(allEntities.map({ ObjectIdentifier($0.type) })).count == expectedCount && Set(allEntities.map({ $0.entityName })).count == expectedCount }, "Ambiguous entity types or entity names were found in the model. Ensure that the entity types and entity names are unique to each other. Entities: \(allEntities)" ) self.modelVersion = modelVersion self.entitiesByConfiguration = actualEntitiesByConfiguration self.allEntities = allEntities if let versionLock = versionLock { Internals.assert( versionLock == VersionLock(entityVersionHashesByName: self.rawModel().entityVersionHashesByName), "A \(Internals.typeName(VersionLock.self)) was provided for the \(Internals.typeName(CoreStoreSchema.self)) with version \"\(modelVersion)\", but the actual hashes do not match. This may result in unwanted migrations or unusable persistent stores.\nExpected lock values: \(versionLock)\nActual lock values: \(VersionLock(entityVersionHashesByName: self.rawModel().entityVersionHashesByName))" ) } else { #if DEBUG Internals.log( .notice, message: "These are hashes for the \(Internals.typeName(CoreStoreSchema.self)) with version name \"\(modelVersion)\". Copy the dictionary below and pass it to the \(Internals.typeName(CoreStoreSchema.self)) initializer's \"versionLock\" argument:\nversionLock: \(VersionLock(entityVersionHashesByName: self.rawModel().entityVersionHashesByName))" ) #endif } } // MARK: - DynamicSchema public let modelVersion: ModelVersion public func rawModel() -> NSManagedObjectModel { return CoreStoreSchema.barrierQueue.sync(flags: .barrier) { if let cachedRawModel = self.cachedRawModel { return cachedRawModel } let rawModel = NSManagedObjectModel() var entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription] = [:] var allCustomGettersSetters: [DynamicEntity: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter]] = [:] var allCustomInitializers: [DynamicEntity: [KeyPathString: CoreStoreManagedObject.CustomInitializer]] = [:] var allFieldCoders: [DynamicEntity: [KeyPathString: Internals.AnyFieldCoder]] = [:] for entity in self.allEntities { let (entityDescription, customGetterSetterByKeyPaths, customInitializerByKeyPaths, fieldCoders) = self.entityDescription( for: entity, initializer: CoreStoreSchema.firstPassCreateEntityDescription(from:in:) ) entityDescriptionsByEntity[entity] = (entityDescription.copy() as! NSEntityDescription) allCustomGettersSetters[entity] = customGetterSetterByKeyPaths allCustomInitializers[entity] = customInitializerByKeyPaths allFieldCoders[entity] = fieldCoders } CoreStoreSchema.secondPassConnectRelationshipAttributes(for: entityDescriptionsByEntity) CoreStoreSchema.thirdPassConnectInheritanceTreeAndIndexes(for: entityDescriptionsByEntity) CoreStoreSchema.fourthPassSynthesizeManagedObjectClasses( for: entityDescriptionsByEntity, allCustomGettersSetters: allCustomGettersSetters, allCustomInitializers: allCustomInitializers, allFieldCoders: allFieldCoders ) rawModel.entities = entityDescriptionsByEntity.values.sorted(by: { $0.name! < $1.name! }) for (configuration, entities) in self.entitiesByConfiguration { rawModel.setEntities( entities .map({ entityDescriptionsByEntity[$0]! }) .sorted(by: { $0.name! < $1.name! }), forConfigurationName: configuration ) } self.cachedRawModel = rawModel return rawModel } } // MARK: Internal internal let entitiesByConfiguration: [String: Set<DynamicEntity>] // MARK: Private private static let barrierQueue = DispatchQueue.concurrent("com.coreStore.coreStoreDataModelBarrierQueue", qos: .userInteractive) private let allEntities: Set<DynamicEntity> private var entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription] = [:] private var customGettersSettersByEntity: [DynamicEntity: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter]] = [:] private var customInitializersByEntity: [DynamicEntity: [KeyPathString: CoreStoreManagedObject.CustomInitializer]] = [:] private var fieldCodersByEntity: [DynamicEntity: [KeyPathString: Internals.AnyFieldCoder]] = [:] private weak var cachedRawModel: NSManagedObjectModel? private func entityDescription( for entity: DynamicEntity, initializer: (DynamicEntity, ModelVersion) -> ( entity: NSEntityDescription, customGetterSetterByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter], customInitializerByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomInitializer], fieldCoders: [KeyPathString: Internals.AnyFieldCoder] ) ) -> ( entity: NSEntityDescription, customGetterSetterByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter], customInitializerByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomInitializer], fieldCoders: [KeyPathString: Internals.AnyFieldCoder] ) { if let cachedEntityDescription = self.entityDescriptionsByEntity[entity] { return ( cachedEntityDescription, self.customGettersSettersByEntity[entity] ?? [:], self.customInitializersByEntity[entity] ?? [:], self.fieldCodersByEntity[entity] ?? [:] ) } let modelVersion = self.modelVersion let (entityDescription, customGetterSetterByKeyPaths, customInitializerByKeyPaths, fieldCoders) = withoutActuallyEscaping( initializer, do: { $0(entity, modelVersion) } ) self.entityDescriptionsByEntity[entity] = entityDescription self.customGettersSettersByEntity[entity] = customGetterSetterByKeyPaths self.customInitializersByEntity[entity] = customInitializerByKeyPaths self.fieldCodersByEntity[entity] = fieldCoders return ( entityDescription, customGetterSetterByKeyPaths, customInitializerByKeyPaths, fieldCoders ) } private static func firstPassCreateEntityDescription(from entity: DynamicEntity, in modelVersion: ModelVersion) -> ( entity: NSEntityDescription, customGetterSetterByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter], customInitializerByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomInitializer], fieldCoders: [KeyPathString: Internals.AnyFieldCoder] ) { let entityDescription = NSEntityDescription() entityDescription.coreStoreEntity = entity entityDescription.name = entity.entityName entityDescription.isAbstract = entity.isAbstract entityDescription.versionHashModifier = entity.versionHashModifier entityDescription.managedObjectClassName = CoreStoreManagedObject.cs_subclassName(for: entity, in: modelVersion) var keyPathsByAffectedKeyPaths: [KeyPathString: Set<KeyPathString>] = [:] var customInitialValuesByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomInitializer] = [:] var customGetterSetterByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter] = [:] var fieldCoders: [KeyPathString: Internals.AnyFieldCoder] = [:] func createProperties(for type: CoreStoreObject.Type) -> [NSPropertyDescription] { var propertyDescriptions: [NSPropertyDescription] = [] for property in type.metaProperties(includeSuperclasses: false) { switch property { case let attribute as FieldAttributeProtocol: Internals.assert( !NSManagedObject.instancesRespond(to: Selector(attribute.keyPath)), "Attribute Property name \"\(String(reflecting: entity.type)).\(attribute.keyPath)\" is not allowed because it collides with \"\(String(reflecting: NSManagedObject.self)).\(attribute.keyPath)\"" ) let entityDescriptionValues = attribute.entityDescriptionValues() let description = NSAttributeDescription() description.name = attribute.keyPath description.attributeType = entityDescriptionValues.attributeType description.isOptional = entityDescriptionValues.isOptional description.defaultValue = entityDescriptionValues.defaultValue description.isTransient = entityDescriptionValues.isTransient description.allowsExternalBinaryDataStorage = entityDescriptionValues.allowsExternalBinaryDataStorage description.versionHashModifier = entityDescriptionValues.versionHashModifier description.renamingIdentifier = entityDescriptionValues.renamingIdentifier let valueTransformer = entityDescriptionValues.valueTransformer description.valueTransformerName = valueTransformer?.transformerName.rawValue propertyDescriptions.append(description) keyPathsByAffectedKeyPaths[attribute.keyPath] = entityDescriptionValues.affectedByKeyPaths customGetterSetterByKeyPaths[attribute.keyPath] = (attribute.getter, attribute.setter) customInitialValuesByKeyPaths[attribute.keyPath] = attribute.initializer fieldCoders[attribute.keyPath] = valueTransformer case let relationship as FieldRelationshipProtocol: Internals.assert( !NSManagedObject.instancesRespond(to: Selector(relationship.keyPath)), "Relationship Property name \"\(String(reflecting: entity.type)).\(relationship.keyPath)\" is not allowed because it collides with \"\(String(reflecting: NSManagedObject.self)).\(relationship.keyPath)\"" ) let entityDescriptionValues = relationship.entityDescriptionValues() let description = NSRelationshipDescription() description.name = relationship.keyPath description.minCount = entityDescriptionValues.minCount description.maxCount = entityDescriptionValues.maxCount description.isOrdered = entityDescriptionValues.isOrdered description.deleteRule = entityDescriptionValues.deleteRule description.versionHashModifier = entityDescriptionValues.versionHashModifier description.renamingIdentifier = entityDescriptionValues.renamingIdentifier propertyDescriptions.append(description) keyPathsByAffectedKeyPaths[relationship.keyPath] = entityDescriptionValues.affectedByKeyPaths case let attribute as AttributeProtocol: Internals.assert( !NSManagedObject.instancesRespond(to: Selector(attribute.keyPath)), "Attribute Property name \"\(String(reflecting: entity.type)).\(attribute.keyPath)\" is not allowed because it collides with \"\(String(reflecting: NSManagedObject.self)).\(attribute.keyPath)\"" ) let entityDescriptionValues = attribute.entityDescriptionValues() let description = NSAttributeDescription() description.name = attribute.keyPath description.attributeType = entityDescriptionValues.attributeType description.isOptional = entityDescriptionValues.isOptional description.defaultValue = entityDescriptionValues.defaultValue description.isTransient = entityDescriptionValues.isTransient description.allowsExternalBinaryDataStorage = entityDescriptionValues.allowsExternalBinaryDataStorage description.versionHashModifier = entityDescriptionValues.versionHashModifier description.renamingIdentifier = entityDescriptionValues.renamingIdentifier propertyDescriptions.append(description) keyPathsByAffectedKeyPaths[attribute.keyPath] = entityDescriptionValues.affectedByKeyPaths customGetterSetterByKeyPaths[attribute.keyPath] = (attribute.getter, attribute.setter) case let relationship as RelationshipProtocol: Internals.assert( !NSManagedObject.instancesRespond(to: Selector(relationship.keyPath)), "Relationship Property name \"\(String(reflecting: entity.type)).\(relationship.keyPath)\" is not allowed because it collides with \"\(String(reflecting: NSManagedObject.self)).\(relationship.keyPath)\"" ) let entityDescriptionValues = relationship.entityDescriptionValues() let description = NSRelationshipDescription() description.name = relationship.keyPath description.minCount = entityDescriptionValues.minCount description.maxCount = entityDescriptionValues.maxCount description.isOrdered = entityDescriptionValues.isOrdered description.deleteRule = entityDescriptionValues.deleteRule description.versionHashModifier = entityDescriptionValues.versionHashModifier description.renamingIdentifier = entityDescriptionValues.renamingIdentifier propertyDescriptions.append(description) keyPathsByAffectedKeyPaths[relationship.keyPath] = entityDescriptionValues.affectedByKeyPaths default: continue } } return propertyDescriptions } entityDescription.properties = createProperties(for: entity.type as! CoreStoreObject.Type) entityDescription.keyPathsByAffectedKeyPaths = keyPathsByAffectedKeyPaths return ( entityDescription, customGetterSetterByKeyPaths, customInitialValuesByKeyPaths, fieldCoders ) } private static func secondPassConnectRelationshipAttributes(for entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription]) { var relationshipsByNameByEntity: [DynamicEntity: [String: NSRelationshipDescription]] = [:] for (entity, entityDescription) in entityDescriptionsByEntity { relationshipsByNameByEntity[entity] = entityDescription.relationshipsByName } func findEntity(for type: CoreStoreObject.Type) -> DynamicEntity { var matchedEntities: Set<DynamicEntity> = [] for (entity, _) in entityDescriptionsByEntity where entity.type == type { matchedEntities.insert(entity) } if matchedEntities.count == 1 { return matchedEntities.first! } if matchedEntities.isEmpty { Internals.abort( "No \(Internals.typeName("Entity<\(type)>")) instance found in the \(Internals.typeName(CoreStoreSchema.self))." ) } else { Internals.abort( "Ambiguous entity types or entity names were found in the model. Ensure that the entity types and entity names are unique to each other. Entities: \(matchedEntities)" ) } } func findInverseRelationshipMatching(destinationEntity: DynamicEntity, destinationKeyPath: String) -> NSRelationshipDescription { for case (destinationKeyPath, let relationshipDescription) in relationshipsByNameByEntity[destinationEntity]! { return relationshipDescription } Internals.abort( "The inverse relationship for \"\(destinationEntity.type).\(destinationKeyPath)\" could not be found. Make sure to set the `inverse:` initializer argument for one of the paired \(Internals.typeName("Relationship.ToOne<T>")), \(Internals.typeName("Relationship.ToManyOrdered<T>")), or \(Internals.typeName("Relationship.ToManyUnozrdered<T>"))" ) } for (entity, entityDescription) in entityDescriptionsByEntity { let relationshipsByName = relationshipsByNameByEntity[entity]! let entityType = entity.type as! CoreStoreObject.Type for property in entityType.metaProperties(includeSuperclasses: false) { switch property { case let relationship as FieldRelationshipProtocol: let (destinationType, destinationKeyPath) = relationship.entityDescriptionValues().inverse let destinationEntity = findEntity(for: destinationType) let description = relationshipsByName[relationship.keyPath]! description.destinationEntity = entityDescriptionsByEntity[destinationEntity]! if let destinationKeyPath = destinationKeyPath { let inverseRelationshipDescription = findInverseRelationshipMatching( destinationEntity: destinationEntity, destinationKeyPath: destinationKeyPath ) description.inverseRelationship = inverseRelationshipDescription inverseRelationshipDescription.inverseRelationship = description inverseRelationshipDescription.destinationEntity = entityDescription description.destinationEntity!.properties = description.destinationEntity!.properties } case let relationship as RelationshipProtocol: let (destinationType, destinationKeyPath) = relationship.entityDescriptionValues().inverse let destinationEntity = findEntity(for: destinationType) let description = relationshipsByName[relationship.keyPath]! description.destinationEntity = entityDescriptionsByEntity[destinationEntity]! if let destinationKeyPath = destinationKeyPath { let inverseRelationshipDescription = findInverseRelationshipMatching( destinationEntity: destinationEntity, destinationKeyPath: destinationKeyPath ) description.inverseRelationship = inverseRelationshipDescription inverseRelationshipDescription.inverseRelationship = description inverseRelationshipDescription.destinationEntity = entityDescription description.destinationEntity!.properties = description.destinationEntity!.properties } default: continue } } } for (entity, entityDescription) in entityDescriptionsByEntity { for (name, relationshipDescription) in entityDescription.relationshipsByName { Internals.assert( relationshipDescription.destinationEntity != nil, "The destination entity for relationship \"\(entity.type).\(name)\" could not be resolved." ) Internals.assert( relationshipDescription.inverseRelationship != nil, "The inverse relationship for \"\(entity.type).\(name)\" could not be found. Make sure to set the `inverse:` argument of the initializer for one of the paired \(Internals.typeName("Relationship.ToOne<T>")), \(Internals.typeName("Relationship.ToManyOrdered<T>")), or \(Internals.typeName("Relationship.ToManyUnozrdered<T>"))" ) } } } private static func thirdPassConnectInheritanceTreeAndIndexes(for entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription]) { func connectBaseEntity(mirror: Mirror, entityDescription: NSEntityDescription) { guard let superclassMirror = mirror.superclassMirror, let superType = superclassMirror.subjectType as? CoreStoreObject.Type, superType != CoreStoreObject.self else { return } for (superEntity, superEntityDescription) in entityDescriptionsByEntity where superEntity.type == superType { if !superEntityDescription.subentities.contains(entityDescription) { superEntityDescription.subentities.append(entityDescription) } connectBaseEntity(mirror: superclassMirror, entityDescription: superEntityDescription) } } for (entity, entityDescription) in entityDescriptionsByEntity { connectBaseEntity( mirror: Mirror(reflecting: (entity.type as! CoreStoreObject.Type).meta), entityDescription: entityDescription ) } for (entity, entityDescription) in entityDescriptionsByEntity { if entity.uniqueConstraints.contains(where: { !$0.isEmpty }) { Internals.assert( entityDescription.superentity == nil, "Uniqueness constraints must be defined at the highest level possible." ) entityDescription.uniquenessConstraints = entity.uniqueConstraints.map { $0.map { $0 as NSString } } } guard !entity.indexes.isEmpty else { continue } defer { entityDescription.coreStoreEntity = entity // reserialize } let attributesByName = entityDescription.attributesByName entityDescription.indexes = entity.indexes.map { (compoundIndexes) in return NSFetchIndexDescription.init( name: "_CoreStoreSchema_indexes_\(entityDescription.name!)_\(compoundIndexes.joined(separator: "_"))", elements: compoundIndexes.map { (keyPath) in return NSFetchIndexElementDescription( property: attributesByName[keyPath]!, collationType: .binary ) } ) } } } private static func fourthPassSynthesizeManagedObjectClasses( for entityDescriptionsByEntity: [DynamicEntity: NSEntityDescription], allCustomGettersSetters: [DynamicEntity: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter]], allCustomInitializers: [DynamicEntity: [KeyPathString: CoreStoreManagedObject.CustomInitializer]], allFieldCoders: [DynamicEntity: [KeyPathString: Internals.AnyFieldCoder]] ) { func createManagedObjectSubclass( for entityDescription: NSEntityDescription, customGetterSetterByKeyPaths: [KeyPathString: CoreStoreManagedObject.CustomGetterSetter]?, customInitializers: [KeyPathString: CoreStoreManagedObject.CustomInitializer]? ) { let superEntity = entityDescription.superentity let className = entityDescription.managedObjectClassName! guard case nil = NSClassFromString(className) as! CoreStoreManagedObject.Type? else { return } if let superEntity = superEntity { createManagedObjectSubclass( for: superEntity, customGetterSetterByKeyPaths: superEntity.coreStoreEntity.flatMap({ allCustomGettersSetters[$0] }), customInitializers: superEntity.coreStoreEntity.flatMap({ allCustomInitializers[$0] }) ) } let superClass = Internals.with { () -> CoreStoreManagedObject.Type in if let superClassName = superEntity?.managedObjectClassName, let superClass = NSClassFromString(superClassName) { return superClass as! CoreStoreManagedObject.Type } return CoreStoreManagedObject.self } let managedObjectClass: AnyClass = className.withCString { // Xcode 10.1+ users: You may find this comment due to a crash while debugging on an iPhone XR device (or any A12 device). // This is a known issue that should not occur in archived builds, as the AppStore strips away arm64e build architectures from the binary. So while it crashes on DEBUG, it shouldn't be an issue for live users. // In the meantime, please submit a bug report to Apple and refer to similar discussions here: // - https://github.com/realm/realm-cocoa/issues/6013 // - https://github.com/wordpress-mobile/WordPress-iOS/pull/10400 // - https://github.com/JohnEstropia/CoreStore/issues/291 // If you wish to debug with A12 devices, please use Xcode 10.0 for now. return objc_allocateClassPair(superClass, $0, 0)! } defer { objc_registerClassPair(managedObjectClass) } func capitalize(_ string: String) -> String { return string.replacingCharacters( in: Range(uncheckedBounds: (string.startIndex, string.index(after: string.startIndex))), with: String(string[string.startIndex]).uppercased() ) } for (attributeName, customGetterSetters) in (customGetterSetterByKeyPaths ?? [:]) where customGetterSetters.getter != nil || customGetterSetters.setter != nil { if let getter = customGetterSetters.getter { let getterName = "\(attributeName)" guard class_addMethod( managedObjectClass, NSSelectorFromString(getterName), imp_implementationWithBlock(getter), "@@:") else { Internals.abort("Could not dynamically add getter method \"\(getterName)\" to class \(Internals.typeName(managedObjectClass))") } } if let setter = customGetterSetters.setter { let setterName = "set\(capitalize(attributeName)):" guard class_addMethod( managedObjectClass, NSSelectorFromString(setterName), imp_implementationWithBlock(setter), "v@:@") else { Internals.abort("Could not dynamically add setter method \"\(setterName)\" to class \(Internals.typeName(managedObjectClass))") } } } swizzle_keyPathsForValuesAffectingValueForKey: do { let newSelector = NSSelectorFromString("cs_keyPathsForValuesAffectingValueForKey:") let keyPathsByAffectedKeyPaths = entityDescription.keyPathsByAffectedKeyPaths let keyPathsForValuesAffectingValue: @convention(block) (Any, String) -> Set<String> = { (instance, keyPath) in if let keyPaths = keyPathsByAffectedKeyPaths[keyPath] { return keyPaths } return [] } let origSelector = #selector(CoreStoreManagedObject.keyPathsForValuesAffectingValue(forKey:)) let metaClass: AnyClass = object_getClass(managedObjectClass)! let origMethod = class_getClassMethod(managedObjectClass, origSelector)! let origImp = method_getImplementation(origMethod) let newImp = imp_implementationWithBlock(keyPathsForValuesAffectingValue) if class_addMethod(metaClass, origSelector, newImp, method_getTypeEncoding(origMethod)) { class_replaceMethod(metaClass, newSelector, origImp, method_getTypeEncoding(origMethod)) } else { let newMethod = class_getClassMethod(managedObjectClass, newSelector)! method_exchangeImplementations(origMethod, newMethod) } } swizzle_awakeFromInsert: do { let newSelector = NSSelectorFromString("cs_awakeFromInsert") let awakeFromInsertValue: @convention(block) (Any) -> Void if let customInitializers = customInitializers, !customInitializers.isEmpty { let initializers = Array(customInitializers.values) awakeFromInsertValue = { (instance) in initializers.forEach { $0(instance) } } } else { awakeFromInsertValue = { _ in } } let origSelector = #selector(CoreStoreManagedObject.awakeFromInsert) let origMethod = class_getInstanceMethod(managedObjectClass, origSelector)! let origImp = method_getImplementation(origMethod) let newImp = imp_implementationWithBlock(awakeFromInsertValue) if class_addMethod(managedObjectClass, origSelector, newImp, method_getTypeEncoding(origMethod)) { class_replaceMethod(managedObjectClass, newSelector, origImp, method_getTypeEncoding(origMethod)) } else { let newMethod = class_getInstanceMethod(managedObjectClass, newSelector)! method_exchangeImplementations(origMethod, newMethod) } } } for (dynamicEntity, entityDescription) in entityDescriptionsByEntity { createManagedObjectSubclass( for: entityDescription, customGetterSetterByKeyPaths: allCustomGettersSetters[dynamicEntity], customInitializers: allCustomInitializers[dynamicEntity] ) } allFieldCoders .flatMap({ (_, values) in values }) .reduce( into: [:] as [NSValueTransformerName: Internals.AnyFieldCoder], { (result, element) in result[element.value.transformerName] = element.value } ) .forEach({ (_, fieldCoder) in fieldCoder.register() }) } }
mit
d4b3d29b8052b6f3bfaa4d905d1f124c
51.492885
408
0.616187
6.04274
false
true
false
false
denrase/TimeTracking-iOS
TimeTracking/BackgroundTask.swift
1
1031
// // BackgroundTask.swift // TimeTracking // // Created by Daniel Griesser on 27/05/15. // Copyright (c) 2015 Bytepoets. All rights reserved. // import Foundation import UIKit class BackgroundTask { private let application: UIApplication private var identifier = UIBackgroundTaskInvalid init(application: UIApplication) { self.application = application } class func run(application: UIApplication, handler: (BackgroundTask) -> ()) { // NOTE: The handler must call end() when it is done let backgroundTask = BackgroundTask(application: application) backgroundTask.begin() handler(backgroundTask) } func begin() { self.identifier = application.beginBackgroundTaskWithExpirationHandler { self.end() } } func end() { if (identifier != UIBackgroundTaskInvalid) { application.endBackgroundTask(identifier) } identifier = UIBackgroundTaskInvalid } }
mit
f7aa14a31a66c15d7939fb810f5e1c99
24.170732
81
0.640155
5.260204
false
false
false
false
anhnc55/fantastic-swift-library
Example/Example/MenuController.swift
1
7874
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Material nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material public extension UIViewController { /** A convenience property that provides access to the MenuController. This is the recommended method of accessing the MenuController through child UIViewControllers. */ public var menuController: MenuController? { var viewController: UIViewController? = self while nil != viewController { if viewController is MenuController { return viewController as? MenuController } viewController = viewController?.parentViewController } return nil } } @IBDesignable public class MenuController : UIViewController { /// Reference to the MenuView. public private(set) lazy var menuView: MenuView = MenuView() /** A Boolean property used to enable and disable interactivity with the rootViewController. */ @IBInspectable public var userInteractionEnabled: Bool { get { return rootViewController.view.userInteractionEnabled } set(value) { rootViewController.view.userInteractionEnabled = value } } /** A UIViewController property that references the active main UIViewController. To swap the rootViewController, it is recommended to use the transitionFromRootViewController helper method. */ public private(set) var rootViewController: UIViewController! /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepareView() } /** An initializer that initializes the object with an Optional nib and bundle. - Parameter nibNameOrNil: An Optional String for the nib. - Parameter bundle: An Optional NSBundle where the nib is located. */ public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) prepareView() } /** An initializer for the BarController. - Parameter rootViewController: The main UIViewController. */ public init(rootViewController: UIViewController) { super.init(nibName: nil, bundle: nil) self.rootViewController = rootViewController prepareView() } public override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() layoutSubviews() } /** A method to swap rootViewController objects. - Parameter toViewController: The UIViewController to swap with the active rootViewController. - Parameter duration: A NSTimeInterval that sets the animation duration of the transition. - Parameter options: UIViewAnimationOptions thst are used when animating the transition from the active rootViewController to the toViewController. - Parameter animations: An animation block that is executed during the transition from the active rootViewController to the toViewController. - Parameter completion: A completion block that is execited after the transition animation from the active rootViewController to the toViewController has completed. */ public func transitionFromRootViewController(toViewController: UIViewController, duration: NSTimeInterval = 0.5, options: UIViewAnimationOptions = [], animations: (() -> Void)? = nil, completion: ((Bool) -> Void)? = nil) { rootViewController.willMoveToParentViewController(nil) addChildViewController(toViewController) toViewController.view.frame = rootViewController.view.frame transitionFromViewController(rootViewController, toViewController: toViewController, duration: duration, options: options, animations: animations, completion: { [weak self] (result: Bool) in if let s: MenuController = self { toViewController.didMoveToParentViewController(s) s.rootViewController.removeFromParentViewController() s.rootViewController = toViewController s.rootViewController.view.clipsToBounds = true s.rootViewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] s.view.sendSubviewToBack(s.rootViewController.view) completion?(result) } }) } /** Opens the menu with a callback. - Parameter completion: An Optional callback that is executed when all menu items have been opened. */ public func openMenu(completion: (() -> Void)? = nil) { if true == userInteractionEnabled { userInteractionEnabled = false rootViewController.view.alpha = 0.5 menuView.open(completion) } } /** Closes the menu with a callback. - Parameter completion: An Optional callback that is executed when all menu items have been closed. */ public func closeMenu(completion: (() -> Void)? = nil) { if false == userInteractionEnabled { rootViewController.view.alpha = 1 menuView.close({ [weak self] in self?.userInteractionEnabled = true completion?() }) } } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepareView method to initialize property values and other setup operations. The super.prepareView method should always be called immediately when subclassing. */ public func prepareView() { view.clipsToBounds = true view.contentScaleFactor = MaterialDevice.scale prepareMenuView() prepareRootViewController() } /// Prepares the MenuView. private func prepareMenuView() { menuView.zPosition = 1000 view.addSubview(menuView) } /// A method that prepares the rootViewController. private func prepareRootViewController() { rootViewController.view.clipsToBounds = true rootViewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] prepareViewControllerWithinContainer(rootViewController, container: view) } /** A method that adds the passed in controller as a child of the MenuController within the passed in container view. - Parameter viewController: A UIViewController to add as a child. - Parameter container: A UIView that is the parent of the passed in controller view within the view hierarchy. */ private func prepareViewControllerWithinContainer(viewController: UIViewController?, container: UIView) { if let v: UIViewController = viewController { addChildViewController(v) container.addSubview(v.view) container.sendSubviewToBack(v.view) v.didMoveToParentViewController(self) } } /// Layout subviews. private func layoutSubviews() { rootViewController.view.frame = view.bounds } }
mit
e5a5e0b1263fc7588bf50c880ef4dec9
33.995556
223
0.769876
4.543566
false
false
false
false
bigL055/Routable
Sources/Routale+UIKit.swift
1
2929
// // Routable // // Copyright (c) 2017 linhay - https://github.com/linhay // // 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 import UIKit // MARK: - only swift public extension Routable { /// 解析viewController类型 /// /// - Parameter coin: viewController 路径 /// - Returns: viewController 或者 nil public class func viewController(coin: RoutableCoin,params:[String: Any] = [:]) -> UIViewController? { return object(url: coin.toURL(), params: params) as? UIViewController } /// 解析view类型 /// /// - Parameter coin: view 路径 /// - Returns: view 或者 nil public class func view(coin: RoutableCoin,params:[String: Any] = [:]) -> UIView? { return object(url: coin.toURL(), params: params) as? UIView } } // MARK: - UIKit public extension Routable { /// 解析viewController类型 /// /// - Parameter url: viewController 路径 /// - Returns: viewController 或者 nil @objc public class func viewController(url: URL,params:[String: Any] = [:]) -> UIViewController? { return object(url: url, params: params) as? UIViewController } /// 解析viewController类型 /// /// - Parameter url: viewController 路径 /// - Returns: viewController 或者 nil @objc public class func viewController(str: String,params:[String: Any] = [:]) -> UIViewController? { return object(str: str, params: params) as? UIViewController } /// 解析view类型 /// /// - Parameter url: view 路径 /// - Returns: view 或者 nil @objc public class func view(url: URL,params:[String: Any] = [:]) -> UIView? { return object(url: url, params: params) as? UIView } /// 解析view类型 /// /// - Parameter url: view 路径 /// - Returns: view 或者 nil @objc public class func view(str: String,params:[String: Any] = [:]) -> UIView? { return object(str: str, params: params) as? UIView } }
mit
d5e89cc4fd738ef2cbbac7f0ed206319
33.54878
104
0.683727
4.088023
false
false
false
false
taketo1024/SwiftyAlgebra
Tests/SwmCoreTests/Polynomials/MultivariatePolynomialTests.swift
1
5889
// // PolynomialTests.swift // SwiftyKnotsTests // // Created by Taketo Sano on 2018/04/10. // import XCTest @testable import SwmCore class MPolynomialTests: XCTestCase { struct xy: MultivariatePolynomialIndeterminates { typealias Exponent = MultiIndex<_2> typealias NumberOfIndeterminates = _2 static func symbolOfIndeterminate(at i: Int) -> String { switch i { case 0: return "x" case 1: return "y" default: fatalError() } } } struct x: PolynomialIndeterminate { static let symbol = "x" } typealias xn = EnumeratedPolynomialIndeterminates<x, anySize> typealias A = MultivariatePolynomial<𝐙, xy> typealias B = MultivariatePolynomial<𝐙, xn> func testFiniteVariateIndeterminates() { XCTAssertTrue (xy.isFinite) XCTAssertEqual(xy.numberOfIndeterminates, 2) XCTAssertEqual(xy.degreeOfIndeterminate(at: 0), 1) XCTAssertEqual(xy.degreeOfIndeterminate(at: 1), 1) XCTAssertEqual(xy.degreeOfMonomial(withExponent: [1, 2]), 3) XCTAssertEqual(xy.symbolOfIndeterminate(at: 0), "x") XCTAssertEqual(xy.symbolOfIndeterminate(at: 1), "y") XCTAssertEqual(xy.descriptionOfMonomial(withExponent: [1, 2]), "xy²") } func testInfiniteVariateIndeterminates() { XCTAssertFalse(xn.isFinite) XCTAssertEqual(xn.degreeOfIndeterminate(at: 0), 1) XCTAssertEqual(xn.degreeOfIndeterminate(at: 1), 1) XCTAssertEqual(xn.degreeOfIndeterminate(at: 2), 1) XCTAssertEqual(xn.degreeOfMonomial(withExponent: [0, 2, 2]), 4) XCTAssertEqual(xn.symbolOfIndeterminate(at: 0), "x₀") XCTAssertEqual(xn.symbolOfIndeterminate(at: 1), "x₁") XCTAssertEqual(xn.symbolOfIndeterminate(at: 2), "x₂") XCTAssertEqual(xn.descriptionOfMonomial(withExponent: [1, 0, 3, 4]), "x₀x₂³x₃⁴") } func testInitFromInt() { let a = A(3) XCTAssertTrue(a.isConst) XCTAssertEqual(a.constTerm, A(3)) XCTAssertEqual(a.constCoeff, 3) XCTAssertEqual(a.degree, 0) } func testInitFromIntLiteral() { let a: A = 3 XCTAssertTrue(a.isConst) XCTAssertEqual(a.constTerm, A(3)) XCTAssertEqual(a.constCoeff, 3) XCTAssertEqual(a.degree, 0) } func testInitFromCoeffList() { // 3x²y + 2x + y + 1 let a = A(elements: [.zero: 1, [1, 0]: 2, [0, 1]: 1, [2, 1]: 3]) XCTAssertTrue(!a.isConst) XCTAssertEqual(a.constTerm, A(1)) XCTAssertEqual(a.coeff(1, 0), 2) XCTAssertEqual(a.coeff(0, 1), 1) XCTAssertEqual(a.coeff(2, 1), 3) XCTAssertEqual(a.leadExponent, [2, 1]) } func testCoeff() { let x = A.indeterminate(0) let y = A.indeterminate(1) XCTAssertEqual(x.coeff([1, 0]), 1) XCTAssertEqual(x.coeff([0, 1]), 0) XCTAssertEqual(y.coeff([1, 0]), 0) XCTAssertEqual(y.coeff([0, 1]), 1) } func testConstant() { let a = A(13) let b = A(elements: [[0,0]: 13]) XCTAssertEqual(a, b) } func testDegree() { let a = A(elements: [.zero: 1, [1,2]: 2, [5,2]: 3]) XCTAssertEqual(a.leadExponent, [5,2]) XCTAssertEqual(a.degree, 7) } func testHomogeneous() { let a = A(elements: [[1, 0]: 1, [0, 1]: 1]) XCTAssertTrue(a.isHomogeneous) let b = A(elements: [[2, 0]: 1, [1, 1]: 1, [0, 2]: 2]) XCTAssertTrue(b.isHomogeneous) let c = A(elements: [[2, 0]: 1, [1, 0]: 1, [0, 0]: 1]) XCTAssertFalse(c.isHomogeneous) let d = A(elements: [[2, 0]: 1, [100, 0]: 0]) XCTAssertTrue(d.isHomogeneous) } func testSum() { let a = A(elements: [[0, 0]: 1, [1, 0]: 1, [0, 1]: 1]) // x + y + 1 let b = A(elements: [[1, 0]: -1, [0, 1]: 2, [1, 1]: 3]) // 3xy - x + 2y XCTAssertEqual(a + b, A(elements: [[0, 0]: 1, [0, 1]: 3, [1, 1]: 3])) } func testZero() { let a = A(elements: [[0, 0]: 1, [1, 0]: 1, [0, 1]: 1]) // x + y + 1 XCTAssertEqual(a + A.zero, a) XCTAssertEqual(A.zero + a, a) } func testNeg() { let a = A(elements: [[0, 0]: 1, [1, 0]: 1, [0, 1]: 1]) XCTAssertEqual(-a, A(elements: [[0, 0]: -1, [1, 0]: -1, [0, 1]: -1])) } func testMul() { let a = A(elements: [[1, 0]: 1, [0, 1]: 1]) // x + y let b = A(elements: [[1, 0]: 2, [0, 1]: -1]) // 2x - y XCTAssertEqual(a * b, A(elements: [[2, 0]: 2, [1, 1]: 1, [0, 2]: -1])) } func testId() { let a = A(elements: [[0, 0]: 1, [1, 0]: 1, [0, 1]: 1]) let e = A.identity XCTAssertEqual(a * e, a) XCTAssertEqual(e * a, a) } func testInv() { let a = A(-1) XCTAssertEqual(a.inverse, .some(a)) let b = A(3) XCTAssertNil(b.inverse) let c = A(elements: [[0, 0]: 1, [1, 0]: 1, [0, 1]: 1]) XCTAssertNil(c.inverse) } func testEvaluate() { let a = A(elements: [[0, 0]: 2, [1, 0]: -1, [0, 1]: 2, [1, 1]: 3]) // f(x,y) = 3xy - x + 2y + 2 XCTAssertEqual(a.evaluate(by: 1, 2), 11) // f(1, 2) = 6 - 1 + 4 + 2 } func testMonomialsOfDegree() { let mons = A.monomials(ofDegree: 5) XCTAssertEqual(mons.count, 6) XCTAssertTrue(mons.allSatisfy{ $0.degree == 5 }) } func testSymmetricPolynomial() { XCTAssertEqual(A.elementarySymmetricPolynomial(ofDegree: 0), A(1)) XCTAssertEqual(A.elementarySymmetricPolynomial(ofDegree: 1), A(elements: [[1, 0]: 1, [0, 1]: 1])) XCTAssertEqual(A.elementarySymmetricPolynomial(ofDegree: 2), A(elements: [[1, 1]: 1])) XCTAssertEqual(A.elementarySymmetricPolynomial(ofDegree: 3), .zero) } }
cc0-1.0
a10ba581790319468fc8cfbb679bdecc
32.141243
105
0.548415
3.323513
false
true
false
false
vikingosegundo/Taylor
Taylor/Response.swift
2
3574
// // response.swift // TaylorTest // // Created by Jorge Izquierdo on 19/06/14. // Copyright (c) 2014 Jorge Izquierdo. All rights reserved. // import Foundation public class Response { public var statusLine: String { return status.statusLine() } public var statusCode: Int { return status.rawValue } public var status: HTTPStatus = .OK public var headers = [String:String]() public var body: NSData? public var bodyString: String? { didSet { if headers["Content-Type"] == nil { headers["Content-Type"] = FileTypes.get("txt") } } } var bodyData: NSData { if let b = body { return b } else if bodyString != nil { return NSData(data: bodyString!.dataUsingEncoding(NSUTF8StringEncoding)!) } return NSData() } private let http_protocol: String = "HTTP/1.1" public func redirect(url u: String) { self.status = .Found self.headers["Location"] = u } public func setFile(url: NSURL?) { if let u = url, let data = NSData(contentsOfURL: u) { self.body = data self.headers["Content-Type"] = FileTypes.get(u.pathExtension ?? "") } else { self.setError(.NotFound) } } public func setError(errorStatus: HTTPStatus){ self.status = errorStatus } func headerData() -> NSData { if headers["Content-Length"] == nil{ headers["Content-Length"] = String(bodyData.length) } let startLine = "\(self.http_protocol) \(String(self.statusCode)) \(self.statusLine)\r\n" var headersStr = "" for (k, v) in self.headers { headersStr += "\(k): \(v)\r\n" } headersStr += "\r\n" let finalStr = String(format: startLine+headersStr) return NSMutableData(data: finalStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!) } internal func generateResponse(method: HTTPMethod) -> NSData { let headerData = self.headerData() guard method != .HEAD else { return headerData } return headerData + self.bodyData } } public enum HTTPStatus: Int { case OK = 200 case Created = 201 case Accepted = 202 case MultipleChoices = 300 case MovedPermanently = 301 case Found = 302 case SeeOther = 303 case BadRequest = 400 case Unauthorized = 401 case Forbidden = 403 case NotFound = 404 case InternalServerError = 500 case BadGateway = 502 case ServiceUnavailable = 503 func statusLine() -> String { switch self { case .OK: return "OK" case .Created: return "Created" case .Accepted: return "Accepted" case .MultipleChoices: return "Multiple Choices" case .MovedPermanently: return "Moved Permentantly" case .Found: return "Found" case .SeeOther: return "See Other" case .BadRequest: return "Bad Request" case .Unauthorized: return "Unauthorized" case .Forbidden: return "Forbidden" case .NotFound: return "Not Found" case .InternalServerError: return "Internal Server Error" case .BadGateway: return "Bad Gateway" case .ServiceUnavailable: return "Service Unavailable" } } }
mit
552cfef9f4faabf43fd018e243b6c6a4
25.474074
114
0.567431
4.641558
false
false
false
false
nacuteodor/ProcessTestSummaries
XCResultKit/ActionRecord.swift
1
1562
// // File.swift // // // Created by David House on 6/30/19. // //- ActionRecord // * Kind: object //* Properties: //+ schemeCommandName: String //+ schemeTaskName: String //+ title: String? //+ startedTime: Date //+ endedTime: Date //+ runDestination: ActionRunDestinationRecord //+ buildResult: ActionResult //+ actionResult: ActionResult import Foundation public struct ActionRecord: XCResultObject { public let schemeCommandName: String public let schemeTaskName: String public let title: String? public let startedTime: Date public let endedTime: Date public let runDestination: ActionRunDestinationRecord public let buildResult: ActionResult public let actionResult: ActionResult public init?(_ json: [String: AnyObject]) { do { schemeCommandName = try xcRequired(element: "schemeCommandName", from: json) schemeTaskName = try xcRequired(element: "schemeTaskName", from: json) buildResult = try xcRequired(element: "buildResult", from: json) actionResult = try xcRequired(element: "actionResult", from: json) title = xcOptional(element: "title", from: json) startedTime = try xcRequired(element: "startedTime", from: json) endedTime = try xcRequired(element: "endedTime", from: json) runDestination = try xcRequired(element: "runDestination", from: json) } catch { print("Error parsing ActionRecord: \(error.localizedDescription)") return nil } } }
mit
2012208267ccd59b3cf0a0e81a2e7cee
32.234043
88
0.663892
4.210243
false
false
false
false
Beaver/BeaverCodeGen
Sources/BeaverCodeGen/Core/String+Generator.swift
1
2071
import Foundation extension String { var indented: String { return indented(count: 1) } func indented(count: Int) -> String { let split = self.split(separator: "\n", omittingEmptySubsequences: false) return split.map { chars in let str = String(chars) if str.replacingOccurrences(of: " ", with: "").count == 0 { return "" } else { return BeaverCodeGen.tab(str, count: count) } }.joined(separator: .br) } static let br = "\n" static func br(_ count: Int) -> String { return (0..<count).map { _ in br }.joined() } var br: String { return self + .br } func br(_ count: Int) -> String { return self + String.br(count) } static let tab = " " static func tab(_ count: Int) -> String { return (0..<count).map { _ in tab }.joined() } var tab: String { return self + .tab } func tab(_ count: Int) -> String { return self + String.tab(count) } var typeName: String { let first = String(prefix(1)).capitalized let other = String(dropFirst()) return first + other } var varName: String { let first = String(prefix(1)).lowercased() let other = String(dropFirst()) return first + other } var snakecase: String { let pattern = "([a-z0-9])([A-Z])" guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { fatalError("Couldn't build regex with pattern: \(pattern)") } let range = NSRange(location: 0, length: count) return regex.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "$1_$2").lowercased() } } func br(_ s: String, count: Int = 1) -> String { return "".br(count) + s } func tab(_ s: String, count: Int = 1) -> String { return "".tab(count) + s } func comment(_ s: String) -> String { return "// " + s }
mit
bbb999ee7ffcee42946ce1a049ef22b8
24.567901
118
0.530662
4.044922
false
false
false
false
khizkhiz/swift
benchmark/single-source/RC4.swift
2
2924
//===--- RC4.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 http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test is based on util/benchmarks/RC4, with modifications // for performance measuring. import TestsUtils struct RC4 { var State : [UInt8] var I : UInt8 = 0 var J : UInt8 = 0 init() { State = [UInt8](repeating: 0, count: 256) } mutating func initialize(Key: [UInt8]) { for i in 0..<256 { State[i] = UInt8(i) } var j : UInt8 = 0 for i in 0..<256 { let K : UInt8 = Key[i % Key.count] let S : UInt8 = State[i] j = j &+ S &+ K swapByIndex(i, y: Int(j)) } } mutating func swapByIndex(x: Int, y: Int) { let T1 : UInt8 = State[x] let T2 : UInt8 = State[y] State[x] = T2 State[y] = T1 } mutating func next() -> UInt8 { I = I &+ 1 J = J &+ State[Int(I)] swapByIndex(Int(I), y: Int(J)) return State[Int(State[Int(I)] &+ State[Int(J)]) & 0xFF] } mutating func encrypt(Data: inout [UInt8]) { let cnt = Data.count for i in 0..<cnt { Data[i] = Data[i] ^ next() } } } let RefResults : [UInt8] = [245, 62, 245, 202, 138, 120, 186, 107, 255, 189, 184, 223, 65, 77, 112, 201, 238, 161, 74, 192, 145, 21, 43, 41, 91, 136, 182, 176, 237, 155, 208, 16, 17, 139, 33, 195, 24, 136, 79, 183, 211, 21, 56, 202, 235, 65, 201, 184, 68, 29, 110, 218, 112, 122, 194, 77, 41, 230, 147, 84, 0, 233, 168, 6, 55, 131, 70, 119, 41, 119, 234, 131, 87, 24, 51, 130, 28, 66, 172, 105, 33, 97, 179, 48, 81, 229, 114, 216, 208, 119, 39, 31, 47, 109, 172, 215, 246, 210, 48, 203] @inline(never) public func run_RC4(N: Int) { let messageLen = 100 let iterations = 500 let Secret = "This is my secret message" let Key = "This is my key" let SecretData : [UInt8] = Array(Secret.utf8) let KeyData : [UInt8] = Array(Key.utf8) var LongData : [UInt8] = [UInt8](repeating: 0, count: messageLen) for _ in 1...N { // Generate a long message. for i in 0..<messageLen { LongData[i] = SecretData[i % SecretData.count] } var Enc = RC4() Enc.initialize(KeyData) for _ in 1...iterations { Enc.encrypt(&LongData) } CheckResults(LongData == RefResults, "Incorrect result in RC4") } }
apache-2.0
0c36931f96458c11aedbd20d6240d5b2
27.115385
80
0.51026
3.341714
false
false
false
false
Estimote/iOS-SDK
Examples/swift/LoyaltyStore/LoyaltyStore/Helpers/ExampleOffers.swift
1
922
// // Please report any problems with this app template to [email protected] // func exampleOffers() -> [Any] { let espresso = Offer(name: "Extra Espresso", description: "", cost: 25, image: UIImage.init(named: "extra_espresso")!) let chocolate = Offer(name: "Chocolate", description: "", cost: 25, image: UIImage.init(named: "chocolate")!) let latte = Offer(name: "Caffee Latte", description: "", cost: 25, image: UIImage.init(named: "latte")!) let white_coffee = Offer(name: "White Coffee", description: "", cost: 50, image: UIImage.init(named: "white_coffee")!) let cappuccino = Offer(name: "Cappuccino", description: "", cost: 50, image: UIImage.init(named: "cappuccino")!) let cookies = Offer(name: "Cookies", description: "", cost: 60, image: UIImage.init(named: "cookies")!) return [espresso, chocolate, latte, white_coffee, cappuccino, cookies] }
mit
d891404946eafcc3fc8407d85ba44bff
60.466667
124
0.655098
3.377289
false
false
false
false
pietgk/EuropeanaApp
EuropeanaApp/EuropeanaApp/Classes/Operations/ReachabilityCondition.swift
1
3208
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ import Foundation import SystemConfiguration /** This is a condition that performs a very high-level reachability check. It does *not* perform a long-running reachability check, nor does it respond to changes in reachability. Reachability is evaluated once when the operation to which this is attached is asked about its readiness. */ struct ReachabilityCondition: OperationCondition { static let hostKey = "Host" static let name = "Reachability" static let isMutuallyExclusive = false let host: NSURL init(host: NSURL) { self.host = host } func dependencyForOperation(operation: Operation) -> NSOperation? { return nil } func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { ReachabilityController.requestReachability(host) { reachable in if reachable { completion(.Satisfied) } else { let error = NSError(code: .ConditionFailed, userInfo: [ OperationConditionKey: self.dynamicType.name, self.dynamicType.hostKey: self.host ]) completion(.Failed(error)) } } } } /// A private singleton that maintains a basic cache of `SCNetworkReachability` objects. private class ReachabilityController { static var reachabilityRefs = [String: SCNetworkReachability]() static let reachabilityQueue = dispatch_queue_create("Operations.Reachability", DISPATCH_QUEUE_SERIAL) static func requestReachability(url: NSURL, completionHandler: (Bool) -> Void) { if let host = url.host { dispatch_async(reachabilityQueue) { var ref = self.reachabilityRefs[host] if ref == nil { let hostString = host as NSString ref = SCNetworkReachabilityCreateWithName(nil, hostString.UTF8String) } if let ref = ref { self.reachabilityRefs[host] = ref var reachable = false var flags: SCNetworkReachabilityFlags = [] if SCNetworkReachabilityGetFlags(ref, &flags) { /* Note that this is a very basic "is reachable" check. Your app may choose to allow for other considerations, such as whether or not the connection would require VPN, a cellular connection, etc. */ reachable = flags.contains(.Reachable) } completionHandler(reachable) } else { completionHandler(false) } } } else { completionHandler(false) } } }
mit
d58eb7386c1b9172f1ed3744c2fc6281
33.847826
109
0.569245
5.915129
false
false
false
false
psartzetakis/JRTypedStrings
Source/TypedStringExtensions.swift
1
1745
// // Created by Panagiotis Sartzetakis // http://www.sartzetakis.me // // // GitHub // http://github.com/psartzetakis/JRTypedStrings // // // License // Copyright © 2017 Panagiotis Sartzetakis // Released under an MIT license: http://opensource.org/licenses/MIT // import Foundation import UIKit public extension UINib { /// Returns a UINib object initialized to the nib file in the specified bundle. /// /// - Parameters: /// - type: The type of the nib. /// - name: The name of the nib file. If it is omitted the class name of the type will be used instead. /// - bundle: The bundle in which to search for the nib file. If you specify nil, this method looks for the nib file in the main bundle. /// - Returns: The initialized UINib object. public convenience init<T: UIView>(_ type: T.Type = T.self, name: String? = nil, bundle: Bundle? = nil) { let nibName = name ?? String(describing: type) self.init(nibName: nibName, bundle: bundle) } } public extension UIView { /// Returns a view from a nib file. /// /// - Parameters: /// - type: The type of the view. /// - name: The name of the nib file. If it is omitted the class name of the type will be used instead. /// - bundle: The bundle where the nib is located. If it is ommited the main Bundle will be used. /// - Returns: A type UIView object from a nib file. public class func loadFromNib<T: UIView>(_ type: T.Type = T.self, name: String? = nil, bundle: Bundle = .main) -> T { let nibName = name ?? String(describing: type) let views = bundle.loadNibNamed(nibName, owner: nil, options: nil) return views!.flatMap({ $0 as? T }).first! } }
mit
8c37d997b26adc429308ba5425496113
33.88
142
0.640482
3.875556
false
false
false
false
syoutsey/swift-corelibs-foundation
Foundation/NSCharacterSet.swift
5
11046
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // import CoreFoundation #if os(OSX) || os(iOS) let kCFCharacterSetControl = CFCharacterSetPredefinedSet.Control let kCFCharacterSetWhitespace = CFCharacterSetPredefinedSet.Whitespace let kCFCharacterSetWhitespaceAndNewline = CFCharacterSetPredefinedSet.WhitespaceAndNewline let kCFCharacterSetDecimalDigit = CFCharacterSetPredefinedSet.DecimalDigit let kCFCharacterSetLetter = CFCharacterSetPredefinedSet.Letter let kCFCharacterSetLowercaseLetter = CFCharacterSetPredefinedSet.LowercaseLetter let kCFCharacterSetUppercaseLetter = CFCharacterSetPredefinedSet.UppercaseLetter let kCFCharacterSetNonBase = CFCharacterSetPredefinedSet.NonBase let kCFCharacterSetDecomposable = CFCharacterSetPredefinedSet.Decomposable let kCFCharacterSetAlphaNumeric = CFCharacterSetPredefinedSet.AlphaNumeric let kCFCharacterSetPunctuation = CFCharacterSetPredefinedSet.Punctuation let kCFCharacterSetCapitalizedLetter = CFCharacterSetPredefinedSet.CapitalizedLetter let kCFCharacterSetSymbol = CFCharacterSetPredefinedSet.Symbol let kCFCharacterSetNewline = CFCharacterSetPredefinedSet.Newline let kCFCharacterSetIllegal = CFCharacterSetPredefinedSet.Illegal #endif public class NSCharacterSet : NSObject, NSCopying, NSMutableCopying, NSCoding { typealias CFType = CFCharacterSetRef private var _base = _CFInfo(typeID: CFCharacterSetGetTypeID()) private var _hashValue = CFHashCode(0) private var _buffer = UnsafeMutablePointer<Void>() private var _length = CFIndex(0) private var _annex = UnsafeMutablePointer<Void>() internal var _cfObject: CFType { return unsafeBitCast(self, CFType.self) } internal var _cfMutableObject: CFMutableCharacterSetRef { return unsafeBitCast(self, CFMutableCharacterSetRef.self) } deinit { _CFDeinit(self) } public class func controlCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetControl)._nsObject } public class func whitespaceCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetWhitespace)._nsObject } public class func whitespaceAndNewlineCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetWhitespaceAndNewline)._nsObject } public class func decimalDigitCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetDecimalDigit)._nsObject } public class func letterCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetLetter)._nsObject } public class func lowercaseLetterCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetLowercaseLetter)._nsObject } public class func uppercaseLetterCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetUppercaseLetter)._nsObject } public class func nonBaseCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetNonBase)._nsObject } public class func alphanumericCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetAlphaNumeric)._nsObject } public class func decomposableCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetDecomposable)._nsObject } public class func illegalCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetIllegal)._nsObject } public class func punctuationCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetPunctuation)._nsObject } public class func capitalizedLetterCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetCapitalizedLetter)._nsObject } public class func symbolCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetSymbol)._nsObject } public class func newlineCharacterSet() -> NSCharacterSet { return CFCharacterSetGetPredefined(kCFCharacterSetNewline)._nsObject } public init(range aRange: NSRange) { super.init() _CFCharacterSetInitWithCharactersInRange(_cfMutableObject, CFRangeMake(aRange.location, aRange.length)) } public init(charactersInString aString: String) { super.init() _CFCharacterSetInitWithCharactersInString(_cfMutableObject, aString._cfObject) } public init(bitmapRepresentation data: NSData) { super.init() _CFCharacterSetInitWithBitmapRepresentation(_cfMutableObject, data._cfObject) } public convenience init?(contentsOfFile fName: String) { if let data = NSData(contentsOfFile: fName) { self.init(bitmapRepresentation: data) } else { return nil } } public convenience required init(coder aDecoder: NSCoder) { self.init(charactersInString: "") } public func characterIsMember(aCharacter: unichar) -> Bool { return CFCharacterSetIsCharacterMember(_cfObject, UniChar(aCharacter)) } public var bitmapRepresentation: NSData { get { return CFCharacterSetCreateBitmapRepresentation(kCFAllocatorSystemDefault, _cfObject)._nsObject } } public var invertedSet: NSCharacterSet { get { return CFCharacterSetCreateInvertedSet(kCFAllocatorSystemDefault, _cfObject)._nsObject } } public func longCharacterIsMember(theLongChar: UTF32Char) -> Bool { return CFCharacterSetIsLongCharacterMember(_cfObject, theLongChar) } public func isSupersetOfSet(theOtherSet: NSCharacterSet) -> Bool { return CFCharacterSetIsSupersetOfSet(_cfObject, theOtherSet._cfObject) } public func hasMemberInPlane(thePlane: UInt8) -> Bool { return CFCharacterSetHasMemberInPlane(_cfObject, CFIndex(thePlane)) } public func copyWithZone(zone: NSZone) -> AnyObject { return CFCharacterSetCreateCopy(kCFAllocatorSystemDefault, self._cfObject) } public func mutableCopyWithZone(zone: NSZone) -> AnyObject { return CFCharacterSetCreateMutableCopy(kCFAllocatorSystemDefault, _cfObject)._nsObject } public func encodeWithCoder(aCoder: NSCoder) { } } public class NSMutableCharacterSet : NSCharacterSet { public convenience required init(coder aDecoder: NSCoder) { NSUnimplemented() } public func addCharactersInRange(aRange: NSRange) { CFCharacterSetAddCharactersInRange(_cfMutableObject , CFRangeMake(aRange.location, aRange.length)) } public func removeCharactersInRange(aRange: NSRange) { CFCharacterSetRemoveCharactersInRange(_cfMutableObject , CFRangeMake(aRange.location, aRange.length)) } public func addCharactersInString(aString: String) { CFCharacterSetAddCharactersInString(_cfMutableObject, aString._cfObject) } public func removeCharactersInString(aString: String) { CFCharacterSetRemoveCharactersInString(_cfMutableObject, aString._cfObject) } public func formUnionWithCharacterSet(otherSet: NSCharacterSet) { CFCharacterSetUnion(_cfMutableObject, otherSet._cfObject) } public func formIntersectionWithCharacterSet(otherSet: NSCharacterSet) { CFCharacterSetIntersect(_cfMutableObject, otherSet._cfObject) } public func invert() { CFCharacterSetInvert(_cfMutableObject) } public override class func controlCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.controlCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func whitespaceCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.whitespaceCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func whitespaceAndNewlineCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.whitespaceAndNewlineCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func decimalDigitCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.decimalDigitCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func letterCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.letterCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func lowercaseLetterCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.lowercaseLetterCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func uppercaseLetterCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.uppercaseLetterCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func nonBaseCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.nonBaseCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func alphanumericCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.alphanumericCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func decomposableCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.decomposableCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func illegalCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.illegalCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func punctuationCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.punctuationCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func capitalizedLetterCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.capitalizedLetterCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func symbolCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.symbolCharacterSet().mutableCopy() as! NSMutableCharacterSet } public override class func newlineCharacterSet() -> NSMutableCharacterSet { return NSCharacterSet.newlineCharacterSet().mutableCopy() as! NSMutableCharacterSet } } extension CFCharacterSetRef : _NSBridgable { typealias NSType = NSCharacterSet internal var _nsObject: NSType { return unsafeBitCast(self, NSType.self) } }
apache-2.0
eb45e64d48ea067dacbe453ef20c7681
38.453571
111
0.744251
6.490012
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/Pods/Swiftilities/Pod/Classes/Math/CubicBezier.swift
2
3215
// // CubicBezier.swift // Swiftilities // // Created by Jason Clark on 8/10/17. // /* Derived from IBM's implementation of the CSS function cubic-bezier Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. This licensed material is licensed under the Apache 2.0 license. http://www.apache.org/licenses/LICENSE-2.0. */ import CoreGraphics.CGGeometry // swiftlint:disable identifier_name extension CubicBezier { static func value(for input: CGFloat, controlPoint1: CGPoint, controlPoint2: CGPoint) -> CGFloat { return CubicBezier(p1: controlPoint1, p2: controlPoint2).valueForX(x: input) } } struct CubicBezier { let cx: CGFloat, bx: CGFloat, ax: CGFloat, cy: CGFloat, by: CGFloat, ay: CGFloat init(p1: CGPoint, p2: CGPoint) { self.init(x1: p1.x, y1: p1.y, x2: p2.x, y2: p2.y) } init(x1: CGFloat, y1: CGFloat, x2: CGFloat, y2: CGFloat) { var p1 = CGPoint.zero var p2 = CGPoint.zero // Clamp to interval [0..1] p1.x = max(0.0, min(1.0, x1)) p1.y = max(0.0, min(1.0, y1)) p2.x = max(0.0, min(1.0, x2)) p2.y = max(0.0, min(1.0, y2)) // Implicit first and last control points are (0,0) and (1,1). cx = 3.0 * p1.x bx = 3.0 * (p2.x - p1.x) - cx ax = 1.0 - cx - bx cy = 3.0 * p1.y by = 3.0 * (p2.y - p1.y) - cy ay = 1.0 - cy - by } func valueForX(x: CGFloat) -> CGFloat { let epsilon: CGFloat = 1.0 / 200.0 let xSolved = solveCurveX(x, epsilon: epsilon) let y = sampleCurveY(xSolved) return (y / epsilon).rounded(.toNearestOrAwayFromZero) * epsilon } private func solveCurveX(_ x: CGFloat, epsilon: CGFloat) -> CGFloat { var t0: CGFloat, t1: CGFloat, t2: CGFloat, x2: CGFloat, d2: CGFloat // First try a few iterations of Newton's method -- normally very fast. t2 = x for _ in 0...8 { x2 = sampleCurveX(t2) - x if abs(x2) < epsilon { return t2 } d2 = sampleCurveDerivativeX(t2) if abs(d2) < 1e-6 { break } t2 -= x2 / d2 } // Fall back to the bisection method for reliability. t0 = 0.0 t1 = 1.0 t2 = x if t2 < t0 { return t0 } if t2 > t1 { return t1 } while t0 < t1 { x2 = sampleCurveX(t2) if abs(x2 - x) < epsilon { return t2 } if x > x2 { t0 = t2 } else { t1 = t2 } t2 = (t1 - t0) * 0.5 + t0 } // Failure. return t2 } private func sampleCurveX(_ t: CGFloat) -> CGFloat { // 'ax t^3 + bx t^2 + cx t' expanded using Horner's rule. return ((ax * t + bx) * t + cx) * t } private func sampleCurveY(_ t: CGFloat) -> CGFloat { return ((ay * t + by) * t + cy) * t } private func sampleCurveDerivativeX(_ t: CGFloat) -> CGFloat { return (3.0 * ax * t + 2.0 * bx) * t + cx } }
mit
c5426209efbc6ae0691f8ac71b6bfa26
24.712
109
0.511512
3.316821
false
false
false
false
grafiti-io/SwiftCharts
Examples/AppDelegate.swift
2
4655
// // AppDelegate.swift // Examples // // Created by ischuetz on 08/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if UIDevice.current.userInterfaceIdiom == .pad { let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers.last as! UINavigationController splitViewController.delegate = self if #available(iOS 8.0, *) { navigationController.topViewController?.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem } } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { if let secondaryAsNavController = secondaryViewController as? UINavigationController { if let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController { if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } } } return false } fileprivate func setSplitSwipeEnabled(_ enabled: Bool) { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { let splitViewController = UIApplication.shared.delegate?.window!!.rootViewController as! UISplitViewController splitViewController.presentsWithGesture = enabled } } func splitViewController(_ svc: UISplitViewController, willHide aViewController: UIViewController, with barButtonItem: UIBarButtonItem, for pc: UIPopoverController) { let navigationController = svc.viewControllers[svc.viewControllers.count-1] as! UINavigationController if let topAsDetailController = navigationController.topViewController as? DetailViewController { barButtonItem.title = "Examples" topAsDetailController.navigationItem.setLeftBarButton(barButtonItem, animated: true) } } } // src: http://stackoverflow.com/a/27399688/930450 extension UISplitViewController { func toggleMasterView() { if #available(iOS 8.0, *) { let barButtonItem = self.displayModeButtonItem UIApplication.shared.sendAction(barButtonItem.action!, to: barButtonItem.target, from: nil, for: nil) } } }
apache-2.0
2d0a29bf1169f6495294babf875b99aa
47.489583
285
0.719012
6.157407
false
false
false
false
joearms/joearms.github.io
includes/swift/combined1.swift
1
3126
// combined1.swift // run with: // $ swift combined1.swift import Cocoa class MyButton: NSButton { var onclick: () -> Bool = {() -> Bool in true} func myclick(sender: AnyObject) { self.onclick() } } func make_button(window: NSWindow, _ size:(x:Int, y:Int, width:Int, ht:Int), _ title:String ) -> MyButton { let button = MyButton() button.frame = NSMakeRect(CGFloat(size.x), CGFloat(size.y), CGFloat(size.width), CGFloat(size.ht)) button.title = title button.bezelStyle = .ThickSquareBezelStyle button.target = button button.action = "myclick:" window.contentView!.addSubview(button) return button } func make_entry(window:NSWindow, _ size:(x:Int, y:Int, width:Int, ht:Int), _ str: String ) -> NSTextView { let text = NSTextView(frame: NSMakeRect(10, 140, 40, 20)) text.frame = NSMakeRect(CGFloat(size.x), CGFloat(size.y), CGFloat(size.width), CGFloat(size.ht)) text.string = str text.editable = true text.selectable = true window.contentView!.addSubview(text) return text } func make_text(window:NSWindow, _ size:(x:Int, y:Int, width:Int, ht:Int), _ str: String ) -> NSTextView { let text = NSTextView(frame: NSMakeRect(10, 140, 40, 20)) text.frame = NSMakeRect(CGFloat(size.x), CGFloat(size.y), CGFloat(size.width), CGFloat(size.ht)) text.string = str text.editable = false text.backgroundColor = window.backgroundColor text.selectable = false window.contentView!.addSubview(text) return text } func make_window(w: Int, _ h: Int, _ title: String) -> NSWindow { let window = NSWindow() window.setContentSize(NSSize(width:w, height:h)) window.styleMask = NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask window.opaque = false window.center(); window.title = title return window } class AppDelegate: NSObject, NSApplicationDelegate { let window = make_window(400, 200, "My title") func applicationDidFinishLaunching(aNotification: NSNotification) { let entry1 = make_entry(window, (200, 80, 180, 30), "1") let text1 = make_text(window, (20, 80, 180, 30), "Hello from me") let text2 = make_text(window, (20, 120, 180, 30), "Another field") let button1 = make_button(window, (120, 40, 80, 30), "Click") // make a click function let f1 = {() -> Bool in text1.string = "Callback worked" print(entry1.textStorage!.string) text2.string = entry1.textStorage!.string return true} // button1.onclick = f1 window.makeKeyAndOrderFront(window) window.makeMainWindow() window.level = 1 } } let app = NSApplication.sharedApplication() app.setActivationPolicy(.Regular) let controller = AppDelegate() app.delegate = controller app.run()
mit
ab42a5f8cd5cc686b887eb4a0399452c
28.490566
76
0.604607
3.927136
false
false
false
false
S2dentik/Taylor
TaylorFrameworkTests/TemperTests/NumberOfLinesInMethodRuleTests.swift
4
2535
// // NumberOfLinesInMethodRuleTests.swift // Temper // // Created by Mihai Seremet on 9/10/15. // Copyright © 2015 Yopeso. All rights reserved. // import Nimble import Quick @testable import TaylorFramework class NumberOfLinesInMethodRuleTests: QuickSpec { let rule = NumberOfLinesInMethodRule() override func spec() { describe("Number Of Lines In Method Rule") { it("should return true and nil when number of lines in smaller than the limit") { let component = Component(type: ComponentType.function, range: ComponentRange(sl: 1, el: self.rule.limit - 1)) let result = self.rule.checkComponent(component) expect(result.isOk).to(beTrue()) expect(result.message).to(beNil()) expect(result.value).to(equal(18)) } it("should return false and message when number of lines in bigger than the limit") { let component = Component(type: ComponentType.function, range: ComponentRange(sl: 1, el: self.rule.limit + 2)) let result = self.rule.checkComponent(component) expect(result.isOk).to(beFalse()) expect(result.message).toNot(beNil()) expect(result.value).to(equal(21)) } it("should not check the non-function components") { let component = Component(type: .for, range: ComponentRange(sl: 0, el: 0)) let result = self.rule.checkComponent(component) expect(result.isOk).to(beTrue()) expect(result.message).to(beNil()) expect(result.value).to(beNil()) } it("should delete the redundant lines and return the correct number of lines") { let component = Component(type: .function, range: ComponentRange(sl: 1, el: 100)) _ = component.makeComponent(type: .emptyLines, range: ComponentRange(sl: 2, el: 5)) _ = component.makeComponent(type: .comment, range: ComponentRange(sl: 6, el: 40)) _ = component.makeComponent(type: .if, range: ComponentRange(sl: 50, el: 60)).makeComponent(type: .comment, range: ComponentRange(sl: 55, el: 59)) let result = self.rule.checkComponent(component) expect(result.value).to(equal(55)) } it("should set the priority") { self.rule.priority = 4 expect(self.rule.priority).to(equal(4)) } } } }
mit
fd8f92b7011f4e4de66ac7e31ea57f22
47.730769
162
0.593923
4.280405
false
true
false
false
Diederia/project
Pods/JTAppleCalendar/Sources/JTAppleCalendarLayout.swift
1
22253
// // JTAppleCalendarLayout.swift // JTAppleCalendar // // Created by JayT on 2016-03-01. // Copyright © 2016 OS-Tech. All rights reserved. // /// Methods in this class are meant to be overridden and will be called by its collection view to gather layout information. open class JTAppleCalendarLayout: UICollectionViewLayout, JTAppleCalendarLayoutProtocol { let errorDelta: CGFloat = 0.0000001 var itemSize: CGSize = CGSize.zero var headerReferenceSize: CGSize = CGSize.zero var scrollDirection: UICollectionViewScrollDirection = .horizontal var maxMissCount: Int = 0 var cellCache: [Int: [UICollectionViewLayoutAttributes]] = [:] var headerCache: [Int: UICollectionViewLayoutAttributes] = [:] var sectionSize: [CGFloat] = [] var lastWrittenCellAttribute: UICollectionViewLayoutAttributes? var isPreparing = false var stride: CGFloat = 0 var maxSections: Int { get { return monthMap.count } } var monthData: [Month] { get { return delegate.monthInfo } } var monthMap: [Int: Int] { get { return delegate.monthMap } } var numberOfRows: Int { get { return delegate.numberOfRows() } } var strictBoundaryRulesShouldApply: Bool { get { return (thereAreHeaders || delegate.hasStrictBoundaries()) && isPreparing } } var thereAreHeaders: Bool { get { return delegate.registeredHeaderViews.count > 0 } } weak var delegate: JTAppleCalendarDelegateProtocol! var currentHeader: (section: Int, size: CGSize)? // Tracks the current header size var currentCell: (section: Int, itemSize: CGSize)? // Tracks the current cell size var contentHeight: CGFloat = 0 // Content height of calendarView var contentWidth: CGFloat = 0 // Content wifth of calendarView var xCellOffset: CGFloat = 0 var yCellOffset: CGFloat = 0 var daysInSection: [Int: Int] = [:] // temporary caching init(withDelegate delegate: JTAppleCalendarDelegateProtocol) { super.init() self.delegate = delegate } /// Tells the layout object to update the current layout. open override func prepare() { if !cellCache.isEmpty { return } isPreparing = true maxMissCount = scrollDirection == .horizontal ? maxNumberOfRowsPerMonth : maxNumberOfDaysInWeek if scrollDirection == .vertical { verticalStuff() } else { horizontalStuff() } // Get rid of header data if dev didnt register headers. // The were used for calculation but are not needed to be displayed if !thereAreHeaders { headerCache.removeAll() } daysInSection.removeAll() // Clear chache isPreparing = false } func horizontalStuff() { var section = 0 var totalDayCounter = 0 var headerGuide = 0 let fullSection = numberOfRows * 7 var extra = 0 for aMonth in monthData { for numberOfDaysInCurrentSection in aMonth.sections { // Generate and cache the headers let sectionIndexPath = IndexPath(item: 0, section: section) if let aHeaderAttr = layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: sectionIndexPath) { headerCache[section] = aHeaderAttr if strictBoundaryRulesShouldApply { contentWidth += aHeaderAttr.frame.width yCellOffset = aHeaderAttr.frame.height } } // Generate and cache the cells for item in 0..<numberOfDaysInCurrentSection { let indexPath = IndexPath(item: item, section: section) if let attribute = deterimeToApplyAttribs(at: indexPath) { if cellCache[section] == nil { cellCache[section] = [] } cellCache[section]!.append(attribute) lastWrittenCellAttribute = attribute xCellOffset += attribute.frame.width if strictBoundaryRulesShouldApply { headerGuide += 1 if numberOfDaysInCurrentSection - 1 == item || headerGuide % 7 == 0 { // We are at the last item in the section // && if we have headers headerGuide = 0 xCellOffset = 0 yCellOffset += attribute.frame.height } } else { totalDayCounter += 1 extra += 1 if totalDayCounter % fullSection == 0 { // If you have a full section xCellOffset = 0 yCellOffset = 0 contentWidth += attribute.frame.width * 7 stride = contentWidth sectionSize.append(contentWidth) } else { if totalDayCounter >= delegate.totalDays { contentWidth += attribute.frame.width * 7 sectionSize.append(contentWidth) } if totalDayCounter % 7 == 0 { xCellOffset = 0 yCellOffset += attribute.frame.height } } } } } // Save the content size for each section if strictBoundaryRulesShouldApply { sectionSize.append(contentWidth) stride = sectionSize[section] } section += 1 } } contentHeight = self.collectionView!.bounds.size.height } func verticalStuff() { var section = 0 var totalDayCounter = 0 var headerGuide = 0 for aMonth in monthData { for numberOfDaysInCurrentSection in aMonth.sections { // Generate and cache the headers let sectionIndexPath = IndexPath(item: 0, section: section) if strictBoundaryRulesShouldApply { if let aHeaderAttr = layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: sectionIndexPath) { headerCache[section] = aHeaderAttr yCellOffset += aHeaderAttr.frame.height contentHeight += aHeaderAttr.frame.height } } // Generate and cache the cells for item in 0..<numberOfDaysInCurrentSection { let indexPath = IndexPath(item: item, section: section) if let attribute = deterimeToApplyAttribs(at: indexPath) { if cellCache[section] == nil { cellCache[section] = [] } cellCache[section]!.append(attribute) lastWrittenCellAttribute = attribute xCellOffset += attribute.frame.width if strictBoundaryRulesShouldApply { headerGuide += 1 if headerGuide % 7 == 0 || numberOfDaysInCurrentSection - 1 == item { // We are at the last item in the // section && if we have headers headerGuide = 0 xCellOffset = 0 yCellOffset += attribute.frame.height contentHeight += attribute.frame.height } } else { totalDayCounter += 1 if totalDayCounter % 7 == 0 { xCellOffset = 0 yCellOffset += attribute.frame.height contentHeight += attribute.frame.height } else if totalDayCounter == delegate.totalDays { contentHeight += attribute.frame.height } } } } // Save the content size for each section sectionSize.append(contentHeight) section += 1 } } contentWidth = self.collectionView!.bounds.size.width } /// Returns the width and height of the collection view’s contents. /// The width and height of the collection view’s contents. open override var collectionViewContentSize: CGSize { return CGSize(width: contentWidth, height: contentHeight) } /// Returns the layout attributes for all of the cells /// and views in the specified rectangle. override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let startSectionIndex = startIndexFrom(rectOrigin: rect.origin) // keep looping until there were no interception rects var attributes: [UICollectionViewLayoutAttributes] = [] var beganIntercepting = false var missCount = 0 for sectionIndex in startSectionIndex..<cellCache.count { if let validSection = cellCache[sectionIndex], validSection.count > 0 { // Add header view attributes if thereAreHeaders { if headerCache[sectionIndex]!.frame.intersects(rect) { attributes.append(headerCache[sectionIndex]!) } } for val in validSection { if val.frame.intersects(rect) { missCount = 0 beganIntercepting = true attributes.append(val) } else { missCount += 1 // If there are at least 8 misses in a row // since intercepting began, then this // section has no more interceptions. // So break if missCount > maxMissCount && beganIntercepting { break } } } if missCount > maxMissCount && beganIntercepting { break }// Also break from outter loop } } return attributes } /// Returns the layout attributes for the item at the specified index /// path. A layout attributes object containing the information to apply /// to the item’s cell. override open func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { // If this index is already cached, then return it else, // apply a new layout attribut to it if let alreadyCachedCellAttrib = cellCache[indexPath.section], indexPath.item < alreadyCachedCellAttrib.count, indexPath.item >= 0 { return alreadyCachedCellAttrib[indexPath.item] } return deterimeToApplyAttribs(at: indexPath) } func deterimeToApplyAttribs(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let monthIndex = monthMap[indexPath.section]! let numberOfDays = numberOfDaysInSection(monthIndex) // return nil on invalid range if !(0...maxSections ~= indexPath.section) || !(0...numberOfDays ~= indexPath.item) { // JT101 look at the ranges return nil } let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath) applyLayoutAttributes(attr) return attr } /// Returns the layout attributes for the specified supplementary view. open override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath) if let alreadyCachedHeaderAttrib = headerCache[indexPath.section] { return alreadyCachedHeaderAttrib } let headerSize = cachedHeaderSizeForSection(indexPath.section) switch scrollDirection { case .horizontal: let modifiedSize = sizeForitemAtIndexPath(indexPath) attributes.frame = CGRect(x: contentWidth, y: 0, width: modifiedSize.width * 7, height: headerSize.height) case .vertical: // Use the calculaed header size and force the width // of the header to take up 7 columns // We cache the header here so we dont call the // delegate so much let modifiedSize = CGSize(width: collectionView!.frame.width, height: headerSize.height) attributes.frame = CGRect(x: 0, y: yCellOffset, width: modifiedSize.width, height: modifiedSize.height) } if attributes.frame == CGRect.zero { return nil } return attributes } func applyLayoutAttributes(_ attributes: UICollectionViewLayoutAttributes) { if attributes.representedElementKind != nil { return } // Calculate the item size let size = sizeForitemAtIndexPath(attributes.indexPath) attributes.frame = CGRect(x: xCellOffset + stride, y: yCellOffset, width: size.width, height: size.height) } func numberOfDaysInSection(_ index: Int) -> Int { if let days = daysInSection[index] { return days } let days = monthData[index].numberOfDaysInMonthGrid daysInSection[index] = days return days } func cachedHeaderSizeForSection(_ section: Int) -> CGSize { // We cache the header here so we dont call the delegate so much var headerSize = CGSize.zero if let cachedHeader = currentHeader, cachedHeader.section == section { headerSize = cachedHeader.size } else { headerSize = delegate.referenceSizeForHeaderInSection(section) currentHeader = (section, headerSize) } return headerSize } func sizeForitemAtIndexPath(_ indexPath: IndexPath) -> CGSize { if let cachedCell = currentCell, cachedCell.section == indexPath.section { if !strictBoundaryRulesShouldApply, scrollDirection == .horizontal, cellCache.count > 0 { return cellCache[0]?[0].size ?? CGSize.zero } else { return cachedCell.itemSize } } var size: CGSize = CGSize.zero if let _ = delegate.itemSize { if scrollDirection == .vertical { size = itemSize } else { size.width = itemSize.width var headerSize = CGSize.zero if strictBoundaryRulesShouldApply { headerSize = cachedHeaderSizeForSection(indexPath.section) } let currentMonth = monthData[monthMap[indexPath.section]!] size.height = (collectionView!.frame.height - headerSize.height) / CGFloat(currentMonth.maxNumberOfRowsForFull( developerSetRows: numberOfRows)) currentCell = (section: indexPath.section, itemSize: size) } } else { // Get header size if it alrady cached var headerSize = CGSize.zero if strictBoundaryRulesShouldApply { headerSize = cachedHeaderSizeForSection(indexPath.section) } var height: CGFloat = 0 let totalNumberOfRows = monthData[monthMap[indexPath.section]!].rows let currentMonth = monthData[monthMap[indexPath.section]!] let monthSection = currentMonth.sectionIndexMaps[indexPath.section]! let numberOfSections = CGFloat(totalNumberOfRows) / CGFloat(numberOfRows) let fullSections = Int(numberOfSections) let numberOfRowsForSection: Int if scrollDirection == .horizontal { if strictBoundaryRulesShouldApply { numberOfRowsForSection = currentMonth.maxNumberOfRowsForFull(developerSetRows: numberOfRows) } else { numberOfRowsForSection = numberOfRows } height = (collectionView!.frame.height - headerSize.height) / CGFloat(numberOfRowsForSection) } else { if monthSection + 1 <= fullSections || !strictBoundaryRulesShouldApply { numberOfRowsForSection = numberOfRows } else { numberOfRowsForSection = totalNumberOfRows - (monthSection * numberOfRows) } height = (collectionView!.frame.height - headerSize.height) / CGFloat(numberOfRowsForSection) } size = CGSize(width: itemSize.width, height: height) currentCell = (section: indexPath.section, itemSize: size) } return size } func sizeOfSection(_ section: Int) -> CGFloat { switch scrollDirection { case .horizontal: return cellCache[section]![0].frame.width * CGFloat(maxNumberOfDaysInWeek) case .vertical: let headerSizeOfSection = headerCache.count > 0 ? headerCache[section]!.frame.height : 0 return cellCache[section]![0].frame.height * CGFloat(numberOfRowsForMonth(section)) + headerSizeOfSection } } func numberOfRowsForMonth(_ index: Int) -> Int { let monthIndex = monthMap[index]! return monthData[monthIndex].rows } func startIndexFrom(rectOrigin offset: CGPoint) -> Int { let key = scrollDirection == .horizontal ? offset.x : offset.y return startIndexBinarySearch(sectionSize, offset: key) } func sizeOfContentForSection(_ section: Int) -> CGFloat { return sizeOfSection(section) } // func sectionFromRectOffset(_ offset: CGPoint) -> Int { // let theOffet = scrollDirection == .horizontal ? offset.x : offset.y // return sectionFromOffset(theOffet) // } func sectionFromOffset(_ theOffSet: CGFloat) -> Int { var val: Int = 0 for (index, sectionSizeValue) in sectionSize.enumerated() { if abs(theOffSet - sectionSizeValue) < errorDelta { continue } if theOffSet < sectionSizeValue { val = index break } } return val } func startIndexBinarySearch<T: Comparable>(_ val: [T], offset: T) -> Int { if val.count < 3 { return 0 } // If the range is less than 2 just break here. var midIndex: Int = 0 var startIndex = 0 var endIndex = val.count - 1 while startIndex < endIndex { midIndex = startIndex + (endIndex - startIndex) / 2 if midIndex + 1 >= val.count || offset >= val[midIndex] && offset < val[midIndex + 1] || val[midIndex] == offset { break } else if val[midIndex] < offset { startIndex = midIndex + 1 } else { endIndex = midIndex } } return midIndex } /// Returns an object initialized from data in a given unarchiver. /// self, initialized using the data in decoder. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Returns the content offset to use after an animation /// layout update or change. /// - Parameter proposedContentOffset: The proposed point for the /// upper-left corner of the visible content /// - returns: The content offset that you want to use instead open override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { if let lastOffsetIndex = delegate.lastIndexOffset { delegate.lastIndexOffset = nil switch lastOffsetIndex.1 { case .supplementaryView: if let headerAttr = layoutAttributesForSupplementaryView(ofKind: UICollectionElementKindSectionHeader, at: lastOffsetIndex.0) { return scrollDirection == .horizontal ? CGPoint(x: headerAttr.frame.origin.x, y: 0) : CGPoint(x: 0, y: headerAttr.frame.origin.y) } case .cell: if let cellAttr = layoutAttributesForItem(at: lastOffsetIndex.0) { return scrollDirection == .horizontal ? CGPoint(x: cellAttr.frame.origin.x, y: 0) : CGPoint(x: 0, y: cellAttr.frame.origin.y) } default: break } } return proposedContentOffset } func clearCache() { headerCache.removeAll() cellCache.removeAll() sectionSize.removeAll() currentHeader = nil currentCell = nil lastWrittenCellAttribute = nil xCellOffset = 0 yCellOffset = 0 contentHeight = 0 contentWidth = 0 stride = 0 } }
mit
54017aedf4b61c8b8a104837a6f53540
41.454198
151
0.550975
6.015684
false
false
false
false
USAssignmentWarehouse/EnglishNow
EnglishNow/Model/Profile/Review.swift
1
3906
// // Review.swift // EnglishNow // // Created by GeniusDoan on 6/29/17. // Copyright © 2017 IceTeaViet. All rights reserved. // import Foundation class Review: NSObject, NSCoding { var partner: String! var photoPartner: String! var comment: String! var ratings: Rating! var gift: Gift! var rating: Double! var recordFileName: String! override init() { super.init() partner = "" photoPartner = "man" comment = "" ratings = Rating() gift = Gift() rating = 0 recordFileName = "" } func encode(with aCoder: NSCoder) { aCoder.encode(partner, forKey: "partner") aCoder.encode(photoPartner, forKey: "photoPartner") aCoder.encode(comment, forKey: "comment") aCoder.encode(ratings, forKey: "ratings") aCoder.encode(gift, forKey: "gift") aCoder.encode(rating, forKey: "rating") aCoder.encode(recordFileName, forKey: "recordFileName") } required init?(coder aDecoder: NSCoder) { partner = aDecoder.decodeObject(forKey: "partner") as! String photoPartner = aDecoder.decodeObject(forKey: "photoPartner") as! String comment = aDecoder.decodeObject(forKey: "comment") as! String ratings = aDecoder.decodeObject(forKey: "ratings") as! Rating gift = aDecoder.decodeObject(forKey: "gift") as! Gift rating = aDecoder.decodeObject(forKey: "rating") as! Double recordFileName = aDecoder.decodeObject(forKey: "recordFileName") as! String } init(dictionary: NSDictionary) { super.init() if let partner = dictionary["partner"] as? String { self.partner = partner } else { partner = "" } if let photo = dictionary["photo_partner"] as? String { self.photoPartner = photo } else { photoPartner = "" } if let comment = dictionary["comment"] as? String { self.comment = comment } else { comment = "" } if let statsDictionary = dictionary["ratings"] as? NSDictionary { self.ratings = Rating(dictionary: statsDictionary) } else { ratings = Rating() } if let giftDictionary = dictionary["gift"] as? NSDictionary { self.gift = Gift(dictionary: giftDictionary) } else { gift = Gift() } if let rating = dictionary["rating"] as? Double { self.rating = rating } else { rating = 0 } if let recordFileName = dictionary["recordFileName"] as? String { self.recordFileName = recordFileName } else { recordFileName = "" } } func dictionary() -> [String: AnyObject] { var dict = [String: AnyObject]() dict.updateValue(partner as AnyObject, forKey: "partner") dict.updateValue(photoPartner as AnyObject, forKey: "photo_partner") dict.updateValue(comment as AnyObject, forKey: "comment") if let ratings = ratings { dict.updateValue(ratings.dictionary() as AnyObject, forKey: "ratings") } if let gift = gift { dict.updateValue(gift.dictionary() as AnyObject, forKey: "gift") } dict.updateValue(rating as AnyObject, forKey: "rating") dict.updateValue(recordFileName as AnyObject, forKey: "recordFileName") return dict } class func arrayDictionary(reviews: [Review]) -> [[String: AnyObject]] { var array = [[String: AnyObject]]() for review in reviews { array.append(review.dictionary()) } return array } }
apache-2.0
312a8759ac5335048ec82d97c817d02d
28.80916
83
0.559027
4.803198
false
false
false
false
bryan1anderson/iMessage-to-Day-One-Importer
iMessage Importer/ImportViewController.swift
1
16157
// // ImportViewController.swift // iMessage Importer // // Created by Bryan on 9/1/17. // Copyright © 2017 Bryan Lloyd Anderson. All rights reserved. // import Cocoa enum ImportType { case developer case user } class ImportViewController: NSViewController { // @IBOutlet weak var stackPickerRanges: NSStackView! @IBOutlet weak var buttonImportAll: NSButton! @IBOutlet weak var buttonCancel: NSButton! @IBOutlet weak var dateDefaultStartPicker: NSDatePicker! var shouldStopBeforeNextDate = false // @IBOutlet weak var dateOldStartPicker: NSDatePicker! // @IBOutlet weak var dateOldEndPicker: NSDatePicker! // // @IBOutlet weak var dateiMessageStartPicker: NSDatePicker! // @IBOutlet weak var dateiMessageEndPicker: NSDatePicker! // // // @IBOutlet weak var buttonImportOld: NSButton! // @IBOutlet weak var buttonImportiMessages: NSButton! @IBOutlet weak var labelStatus: NSTextField! @IBOutlet weak var labelStatusMessageTitle: NSTextField! let importQueue = DispatchQueue(label: "com.imessagesimport", qos: .utility) override func viewDidLoad() { super.viewDidLoad() setDatePickersInitialValue() DispatchQueue.main.async { self.labelStatus.stringValue = "" } setImportType() DispatchQueue.main.async { self.buttonImportAll.alternateTitle = "Cancel" } // importOld() // Do view setup here. } var importType: ImportType = .user { didSet { setImportType() } } func setImportType() { // switch importType { // case .developer: // stackPickerRanges.isHidden = false // case .user: // stackPickerRanges.isHidden = true // } } @IBAction func clickedImportOld(_ sender: NSButton) { } @IBAction func clickedImportiMessages(_ sender: NSButton) { } @IBAction func changedDateOldStart(_ sender: NSDatePicker) { self.dateOldStart = sender.dateValue } @IBAction func changedDateOldEnd(_ sender: NSDatePicker) { self.dateOldEnd = sender.dateValue } @IBAction func changedDateiMessagesStart(_ sender: NSDatePicker) { self.dateiMessagesStart = sender.dateValue } @IBAction func changedDateiMessagesEnd(_ sender: NSDatePicker) { self.dateiMessagesEnd = sender.dateValue } @IBAction func changedDefaultStartDate(_ sender: NSDatePicker) { self.dateDefaultStart = sender.dateValue } var currentWorkItems: [DispatchWorkItem] = [] @IBAction func importAllNotImportedDates(_ sender: NSButton) { self.buttonCancel.isHidden = false self.buttonImportAll.isEnabled = false NSAnimationContext.runAnimationGroup({ (context) in context.duration = 0.5 self.buttonCancel.animator().alphaValue = 1 }) { print("completed") } let workItem = DispatchWorkItem { self.importMessagesForAllNonImportedDates() } self.currentWorkItems.append(workItem) importQueue.async { workItem.perform() } } @IBAction func cllickedCancelImport(_ sender: NSButton) { NSApplication.shared().terminate(self) } @IBAction func clickedQuitAfterFinishingDate(_ sender: NSButton) { let alert = NSAlert() alert.informativeText = "All entries for the current date being imported will finish importing, before the next date begins the app will quit. This helps avoid duplicates on days" alert.messageText = "Quit app after current date finishes importing?" alert.addButton(withTitle: "Quit") alert.addButton(withTitle: "Cancel") alert.alertStyle = .warning let willQuit = alert.runModal() == NSAlertFirstButtonReturn if willQuit { self.shouldStopBeforeNextDate = true } } @IBAction func resetImportedDates(_ sender: NSButton) { let alert = NSAlert() alert.informativeText = "Resetting dates will allow dates already imported to be reimported, this can result in duplicates" alert.messageText = "Reset Dates?" alert.addButton(withTitle: "Reset") alert.addButton(withTitle: "Cancel") alert.alertStyle = .warning let willReset = alert.runModal() == NSAlertFirstButtonReturn if willReset { self.importedDates = [] } } } extension ImportViewController { func importOld() { var startC = DateComponents() startC.year = 2014 startC.month = 10 startC.day = 21 var endC = DateComponents() endC.year = 2014 endC.month = 10 endC.day = 23 guard let start = Calendar.current.date(from: startC), let end = Calendar.current.date(from: endC) else { return } importQueue.async { self.importNonImportedOldMessages(startDate: start, endDate: end) } } @objc func importMessagesForAllNonImportedDates() { // self.importDatesMenuItem?.isEnabled = false DispatchQueue.main.async { self.buttonImportAll.isEnabled = false } var startC = DateComponents() startC.year = 2017 startC.month = 8 startC.day = 25 // var endC = DateComponents() // endC.year = 2017 // endC.month = 6 // endC.day = 29 guard var date = self.dateDefaultStart else { return } // let endDate = Calendar.current.date(from: endC) else { return } // first date let endDate = Date().yesterday // last date var importedDates = self.importedDates while date <= endDate { date = Calendar.current.date(byAdding: .day, value: 1, to: date)! let contains = importedDates.contains(where: { Calendar.current.isDate($0, inSameDayAs: date) }) if !contains { print("importing: \(date)") // let stringDate = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .none) DispatchQueue.main.async { self.labelStatus.stringValue = "" self.labelStatusMessageTitle.stringValue = "" } if self.shouldStopBeforeNextDate { NSApplication.shared().terminate(self) return } self.importMessages(date: date) // self.importOldMessages(date: date) importedDates.append(date) self.importedDates = importedDates } else { print("already imported date: \(date)") let formater = DateFormatter() formater.dateStyle = .medium let dateString = formater.string(from: date) DispatchQueue.main.async { self.labelStatus.stringValue = "already imported date: \(dateString)" } } } // self.importDatesMenuItem?.isEnabled = false DispatchQueue.main.async { self.labelStatusMessageTitle.stringValue = "Finished importing" self.buttonCancel.isHidden = true self.buttonImportAll.isEnabled = true } } func importMessages(date: Date) { let group = DispatchGroup() let importer = MessageImporter(date: date) group.enter() // DispatchQueue.global(qos: .userInitiated).async { importer.getMessages { (joins) in guard let joins = joins else { group.leave(); return } self.importChats(chatMessageJoins: joins, completion: { group.leave() }) } // } group.wait() } @objc func importNonImportedOldMessages(startDate: Date, endDate: Date) { // var startC = DateComponents() // startC.year = 2009 // startC.month = 9 // startC.day = 20 // // var endC = DateComponents() // endC.year = 2014 // endC.month = 10 // endC.day = 22 // var endC = DateComponents() // endC.year = 2017 // endC.month = 6 // endC.day = 29 var date = startDate let endDate = endDate.yesterday // guard var date = Calendar.current.date(from: startC), // let endDate = Calendar.current.date(from: endC)?.yesterday else { return } // let endDate = Calendar.current.date(from: endC) else { return } // first date // let endDate = Date().yesterday // last date // var importedDates = self.importedDates while date <= endDate { date = Calendar.current.date(byAdding: .day, value: 1, to: date)! print("importing: \(date)") DispatchQueue.main.async { self.labelStatus.stringValue = "importing: \(date)" } self.importOldMessages(date: date) // let contains = importedDates.contains(where: { Calendar.current.isDate($0, inSameDayAs: date) }) // if !contains { // importMessages(date: date) // importedDates.append(date) // self.importedDates = importedDates // } else { // print("already imported date: \(date)") // } } } func importOldMessages(date: Date) { let importer = SMSImporter(date: date) importer.delegate = self importer.importDbs() } } extension ImportViewController { var importedDates: [Date] { get { let defaults = UserDefaults.standard let importedDates = defaults.object(forKey: "imported_dates") as? [Date] ?? [] return importedDates } set { let defaults = UserDefaults.standard defaults.set(newValue, forKey: "imported_dates") defaults.synchronize() } } func setDatePickersInitialValue() { // if let oldStart = self.dateOldStart { // dateOldStartPicker.dateValue = oldStart // } // // if let oldEnd = self.dateOldEnd { // dateOldEndPicker.dateValue = oldEnd // } // // if let iMessagesStart = self.dateiMessagesStart { // dateiMessageStartPicker.dateValue = iMessagesStart // } // // if let iMessagesEnd = self.dateiMessagesEnd { // dateiMessageEndPicker.dateValue = iMessagesEnd // } if let defaultStart = self.dateDefaultStart { self.dateDefaultStartPicker.dateValue = defaultStart } } var dateDefaultStart: Date? { get { let defaults = UserDefaults.standard let date = defaults.object(forKey: "dateDefaultStart") as? Date return date } set { let defaults = UserDefaults.standard defaults.set(newValue, forKey: "dateDefaultStart") defaults.synchronize() } } var dateOldStart: Date? { get { let defaults = UserDefaults.standard let date = defaults.object(forKey: "dateOldStart") as? Date return date } set { let defaults = UserDefaults.standard defaults.set(newValue, forKey: "dateOldStart") defaults.synchronize() } } var dateOldEnd: Date? { get { let defaults = UserDefaults.standard let date = defaults.object(forKey: "dateOldEnd") as? Date return date } set { let defaults = UserDefaults.standard defaults.set(newValue, forKey: "dateOldEnd") defaults.synchronize() } } var dateiMessagesStart: Date? { get { let defaults = UserDefaults.standard let date = defaults.object(forKey: "dateiMessagesStart") as? Date return date } set { let defaults = UserDefaults.standard defaults.set(newValue, forKey: "dateiMessagesStart") defaults.synchronize() } } var dateiMessagesEnd: Date? { get { let defaults = UserDefaults.standard let date = defaults.object(forKey: "dateiMessagesEnd") as? Date return date } set { let defaults = UserDefaults.standard defaults.set(newValue, forKey: "dateiMessagesEnd") defaults.synchronize() } } } extension ImportViewController: MessageImporterDelegate { func importChats(chatMessageJoins: [ChatMessageJoin], completion: () -> ()) { let group = DispatchGroup() for chatMessageJoin in chatMessageJoins { group.enter() DispatchQueue.global(qos: .utility).async { chatMessageJoin.getReadableString(completion: { (entry) in guard let command = self.createEntryCommand(for: entry) else { group.leave(); return } // print(command) let returned = run(command: command) print(returned) group.leave() }) } } group.wait() completion() } func didGet(chatMessageJoins: [ChatMessageJoin]) { } func didGet(oldGroupJoins: [GroupMessageMemberJoin]) { for chatMessageJoin in oldGroupJoins { chatMessageJoin.getReadableString(completion: { (entry) in guard let command = self.createEntryCommand(for: entry) else { return } // print(command) let returned = run(command: command) print(returned) DispatchQueue.main.sync { self.labelStatusMessageTitle.stringValue = returned } }) } } func createEntryCommand(for entry: Entry) -> String? { let c = Calendar.current.dateComponents([.day, .month, .year], from: entry.date) guard let day = c.day, let month = c.month, let year = c.year else { return nil } let tags = entry.tags.joined(separator: " ") let stringDate = DateFormatter.localizedString(from: entry.date, dateStyle: .medium, timeStyle: .none) let body = "\(entry.title) \(entry.body)" DispatchQueue.main.async { self.labelStatusMessageTitle.stringValue = "Importing: \(stringDate) \(entry.title)" } let photosTags: String let photoAttachments = entry.attachments?.filter({ (attachment) -> Bool in let type = attachment.mimeType.type switch type { case .image: return true default: return false } }) if let attachments = photoAttachments, photoAttachments?.count ?? 0 > 0 { // let names = attachments.flatMap({"'\($0.filename)'"}) let names = attachments.flatMap({ (attachment) -> String? in let filename = attachment.filename.replacingOccurrences(of: " ", with: "\\ ") return filename }) let photos = names.joined(separator: " ") photosTags = " -p \(photos)" } else { photosTags = "" } let command = "/usr/local/bin/dayone2 -j 'iMessages'\(photosTags) --tags='\(tags)' --date='\(month)/\(day)/\(year)' new \'\(body)\'" print(command) return command } }
mit
c8b4e86b9a853cab8c7ec56d79cea380
31.837398
187
0.560535
4.802616
false
false
false
false
Stitch7/mclient
mclient/PrivateMessages/_MessageKit/Models/MessageKitDateFormatter.swift
1
2437
/* MIT License Copyright (c) 2017-2018 MessageKit 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 open class MessageKitDateFormatter { // MARK: - Properties public static let shared = MessageKitDateFormatter() private let formatter = DateFormatter() // MARK: - Initializer private init() {} // MARK: - Methods public func string(from date: Date) -> String { configureDateFormatter(for: date) return formatter.string(from: date) } public func attributedString(from date: Date, with attributes: [NSAttributedString.Key: Any]) -> NSAttributedString { let dateString = string(from: date) return NSAttributedString(string: dateString, attributes: attributes) } open func configureDateFormatter(for date: Date) { switch true { case Calendar.current.isDateInToday(date) || Calendar.current.isDateInYesterday(date): formatter.doesRelativeDateFormatting = true formatter.dateStyle = .short formatter.timeStyle = .short case Calendar.current.isDate(date, equalTo: Date(), toGranularity: .weekOfYear): formatter.dateFormat = "EEEE h:mm a" case Calendar.current.isDate(date, equalTo: Date(), toGranularity: .year): formatter.dateFormat = "E, d MMM, h:mm a" default: formatter.dateFormat = "MMM d, yyyy, h:mm a" } } }
mit
eac5a7f5365f46b05063b6ba4f6f7bcb
35.924242
121
0.71112
4.864271
false
false
false
false
adapter00/FlickableCalendar
FlickableCalendar/Classes/Date+Additional.swift
1
4527
// // NSDate+Format.swift // lnlnApp // // Created by 前田 恭男 on 2015/11/09. // Copyright © 2015年 MTI Ltd. All rights reserved. // import Foundation enum FormatStyle: String { case Hyphen = "yyyy-MM-dd" case Slash = "yyyy/MM/dd" case MonthDayKanji = "MM月dd日" case YearMonthKanji = "yyyy年MM月" case YearMonthDayKanji = "yyyy年MM月dd日" case MonthDaySlash = "MM/dd" case Day = "dd" case YearMonth = "yyyy/MM" } /// 曜日 enum WeekOfDay: Int { case sunday = 1 case monday case tuesday case wednesday case thursday case friday case saturday } extension Date { var placeInWeek:WeekOfDay? { let comps = CalendarSetting.calendar.dateComponents([.weekday], from: self) guard let weekDay = comps.weekday else { return nil } return WeekOfDay(rawValue: weekDay) } static var Today: Date { let date = Date() let cal = Calendar(identifier: Calendar.Identifier.gregorian) let comps = (cal as NSCalendar).components([.year, .month, .day], from: date) return cal.date(from: comps)! } static func convertToString(_ date: Date?, style: FormatStyle) -> String? { guard let d = date else { return nil } // MARK TODO: check date format let formatter = DateFormatter() formatter.locale = Locale(identifier: "ja-JP") formatter.dateFormat = style.rawValue return formatter.string(from: d) } static func dateFromString(_ input: String?, style: FormatStyle) -> Date? { guard let d = input else { return nil } // MARK TODO: check date format let formatter = DateFormatter() formatter.locale = Locale(identifier: "ja-JP") formatter.dateFormat = style.rawValue return formatter.date(from: d) } } // Calculation extension Date { /// 日付に対する曜日(JP)を返す /// - returns: 曜日(月・火...etc) var shortDayInWeek: String { get { let cal: Calendar = Calendar(identifier: Calendar.Identifier.gregorian) let comp: DateComponents = (cal as NSCalendar).components([NSCalendar.Unit.weekday], from: self) let weekday: Int = comp.weekday! let formatter = DateFormatter() formatter.locale = CalendarSetting.locale return formatter.shortWeekdaySymbols[weekday - 1] } } var firstDayInMonth:Date? { let comp = CalendarSetting.calendar.dateComponents([.era,.year,.month,.day], from: self) guard let era = comp.era, let year = comp.year, let month = comp.month else { return nil } return CalendarSetting.calendar.date(from: DateComponents(era:era,year:year,month:month,day:1)) } var toDay:Date? { let comp = CalendarSetting.calendar.dateComponents([.era,.year,.month,.day], from: self) return CalendarSetting.calendar.date(from: comp) } func addDay(_ days: Int) -> Date { let calendar = CalendarSetting.calendar var components = DateComponents() components.day = days return (calendar as NSCalendar).date(byAdding: components, to: self, options: [])! } func addMonth(_ val: Int) -> Date { let calendar: Calendar = CalendarSetting.calendar var comps = (calendar as NSCalendar).components([.year, .month, .day], from: self) comps.month = comps.month! + val return calendar.date(from: comps)! } func isContainSameMonth(_ date: Date) -> Bool { let calendar = CalendarSetting.calendar let day = (calendar as NSCalendar).components([.year, .month], from: self) let day2 = (calendar as NSCalendar).components([.year, .month], from: date) if day.era == day2.era && day.year == day2.year && day.month == day2.month { return true } else { return false } } static func daysBetween(_ start: Date, end: Date) -> Int { let calendar = CalendarSetting.calendar let starDate = calendar.date(from: (calendar as NSCalendar).components([.year, .month, .day], from: start)) let endDate = calendar.date(from: (calendar as NSCalendar).components([.year, .month, .day], from: end)) let comps = (calendar as NSCalendar).components([.day], from: starDate!, to: endDate!, options: NSCalendar.Options(rawValue: 0)) return comps.day! } }
mit
763052f17b4089850c63b5f3421bc142
32.833333
136
0.615987
4.12373
false
false
false
false
xedin/swift
stdlib/public/core/StringUTF8View.swift
1
17056
//===--- StringUTF8.swift - A UTF8 view of String -------------------------===// // // 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 // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of UTF-8 code units. /// /// You can access a string's view of UTF-8 code units by using its `utf8` /// property. A string's UTF-8 view encodes the string's Unicode scalar /// values as 8-bit integers. /// /// let flowers = "Flowers 💐" /// for v in flowers.utf8 { /// print(v) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 240 /// // 159 /// // 146 /// // 144 /// /// A string's Unicode scalar values can be up to 21 bits in length. To /// represent those scalar values using 8-bit integers, more than one UTF-8 /// code unit is often required. /// /// let flowermoji = "💐" /// for v in flowermoji.unicodeScalars { /// print(v, v.value) /// } /// // 💐 128144 /// /// for v in flowermoji.utf8 { /// print(v) /// } /// // 240 /// // 159 /// // 146 /// // 144 /// /// In the encoded representation of a Unicode scalar value, each UTF-8 code /// unit after the first is called a *continuation byte*. /// /// UTF8View Elements Match Encoded C Strings /// ========================================= /// /// Swift streamlines interoperation with C string APIs by letting you pass a /// `String` instance to a function as an `Int8` or `UInt8` pointer. When you /// call a C function using a `String`, Swift automatically creates a buffer /// of UTF-8 code units and passes a pointer to that buffer. The code units /// of that buffer match the code units in the string's `utf8` view. /// /// The following example uses the C `strncmp` function to compare the /// beginning of two Swift strings. The `strncmp` function takes two /// `const char*` pointers and an integer specifying the number of characters /// to compare. Because the strings are identical up to the 14th character, /// comparing only those characters results in a return value of `0`. /// /// let s1 = "They call me 'Bell'" /// let s2 = "They call me 'Stacey'" /// /// print(strncmp(s1, s2, 14)) /// // Prints "0" /// print(String(s1.utf8.prefix(14))) /// // Prints "They call me '" /// /// Extending the compared character count to 15 includes the differing /// characters, so a nonzero result is returned. /// /// print(strncmp(s1, s2, 15)) /// // Prints "-17" /// print(String(s1.utf8.prefix(15))) /// // Prints "They call me 'B" @frozen public struct UTF8View { @usableFromInline internal var _guts: _StringGuts @inlinable @inline(__always) internal init(_ guts: _StringGuts) { self._guts = guts _invariantCheck() } } } extension String.UTF8View { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { // TODO: Ensure index alignment } #endif // INTERNAL_CHECKS_ENABLED } extension String.UTF8View: BidirectionalCollection { public typealias Index = String.Index public typealias Element = UTF8.CodeUnit /// The position of the first code unit if the UTF-8 view is /// nonempty. /// /// If the UTF-8 view is empty, `startIndex` is equal to `endIndex`. @inlinable @inline(__always) public var startIndex: Index { return _guts.startIndex } /// The "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// In an empty UTF-8 view, `endIndex` is equal to `startIndex`. @inlinable @inline(__always) public var endIndex: Index { return _guts.endIndex } /// Returns the next consecutive position after `i`. /// /// - Precondition: The next position is representable. @inlinable @inline(__always) public func index(after i: Index) -> Index { if _fastPath(_guts.isFastUTF8) { return i.nextEncoded } return _foreignIndex(after: i) } @inlinable @inline(__always) public func index(before i: Index) -> Index { precondition(!i.isZeroPosition) if _fastPath(_guts.isFastUTF8) { return i.priorEncoded } return _foreignIndex(before: i) } @inlinable @inline(__always) public func index(_ i: Index, offsetBy n: Int) -> Index { if _fastPath(_guts.isFastUTF8) { _precondition(n + i._encodedOffset <= _guts.count) return i.encoded(offsetBy: n) } return _foreignIndex(i, offsetBy: n) } @inlinable @inline(__always) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { if _fastPath(_guts.isFastUTF8) { // Check the limit: ignore limit if it precedes `i` (in the correct // direction), otherwise must not be beyond limit (in the correct // direction). let iOffset = i._encodedOffset let result = iOffset + n let limitOffset = limit._encodedOffset if n >= 0 { guard limitOffset < iOffset || result <= limitOffset else { return nil } } else { guard limitOffset > iOffset || result >= limitOffset else { return nil } } return Index(_encodedOffset: result) } return _foreignIndex(i, offsetBy: n, limitedBy: limit) } @inlinable @inline(__always) public func distance(from i: Index, to j: Index) -> Int { if _fastPath(_guts.isFastUTF8) { return j._encodedOffset &- i._encodedOffset } return _foreignDistance(from: i, to: j) } /// Accesses the code unit at the given position. /// /// The following example uses the subscript to print the value of a /// string's first UTF-8 code unit. /// /// let greeting = "Hello, friend!" /// let i = greeting.utf8.startIndex /// print("First character's UTF-8 code unit: \(greeting.utf8[i])") /// // Prints "First character's UTF-8 code unit: 72" /// /// - Parameter position: A valid index of the view. `position` /// must be less than the view's end index. @inlinable @inline(__always) public subscript(i: Index) -> UTF8.CodeUnit { String(_guts)._boundsCheck(i) if _fastPath(_guts.isFastUTF8) { return _guts.withFastUTF8 { utf8 in utf8[_unchecked: i._encodedOffset] } } return _foreignSubscript(position: i) } } extension String.UTF8View: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return String(_guts) } } extension String.UTF8View: CustomDebugStringConvertible { public var debugDescription: String { return "UTF8View(\(self.description.debugDescription))" } } extension String { /// A UTF-8 encoding of `self`. @inlinable public var utf8: UTF8View { @inline(__always) get { return UTF8View(self._guts) } set { self = String(newValue._guts) } } /// A contiguously stored null-terminated UTF-8 representation of the string. /// /// To access the underlying memory, invoke `withUnsafeBufferPointer` on the /// array. /// /// let s = "Hello!" /// let bytes = s.utf8CString /// print(bytes) /// // Prints "[72, 101, 108, 108, 111, 33, 0]" /// /// bytes.withUnsafeBufferPointer { ptr in /// print(strlen(ptr.baseAddress!)) /// } /// // Prints "6" public var utf8CString: ContiguousArray<CChar> { if _fastPath(_guts.isFastUTF8) { var result = _guts.withFastCChar { ContiguousArray($0) } result.append(0) return result } return _slowUTF8CString() } @usableFromInline @inline(never) // slow-path internal func _slowUTF8CString() -> ContiguousArray<CChar> { var result = ContiguousArray<CChar>() result.reserveCapacity(self._guts.count + 1) for c in self.utf8 { result.append(CChar(bitPattern: c)) } result.append(0) return result } /// Creates a string corresponding to the given sequence of UTF-8 code units. @available(swift, introduced: 4.0, message: "Please use failable String.init?(_:UTF8View) when in Swift 3.2 mode") @inlinable @inline(__always) public init(_ utf8: UTF8View) { self = String(utf8._guts) } } extension String.UTF8View { @inlinable @inline(__always) public var count: Int { if _fastPath(_guts.isFastUTF8) { return _guts.count } return _foreignCount() } } // Index conversions extension String.UTF8View.Index { /// Creates an index in the given UTF-8 view that corresponds exactly to the /// specified `UTF16View` position. /// /// The following example finds the position of a space in a string's `utf16` /// view and then converts that position to an index in the string's /// `utf8` view. /// /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.firstIndex(of: 32)! /// let utf8Index = String.UTF8View.Index(utf16Index, within: cafe.utf8)! /// /// print(Array(cafe.utf8[..<utf8Index])) /// // Prints "[67, 97, 102, 195, 169]" /// /// If the position passed in `utf16Index` doesn't have an exact /// corresponding position in `utf8`, the result of the initializer is /// `nil`. For example, because UTF-8 and UTF-16 represent high Unicode code /// points differently, an attempt to convert the position of the trailing /// surrogate of a UTF-16 surrogate pair fails. /// /// The next example attempts to convert the indices of the two UTF-16 code /// points that represent the teacup emoji (`"🍵"`). The index of the lead /// surrogate is successfully converted to a position in `utf8`, but the /// index of the trailing surrogate is not. /// /// let emojiHigh = cafe.utf16.index(after: utf16Index) /// print(String.UTF8View.Index(emojiHigh, within: cafe.utf8)) /// // Prints "Optional(String.Index(...))" /// /// let emojiLow = cafe.utf16.index(after: emojiHigh) /// print(String.UTF8View.Index(emojiLow, within: cafe.utf8)) /// // Prints "nil" /// /// - Parameters: /// - sourcePosition: A position in a `String` or one of its views. /// - target: The `UTF8View` in which to find the new position. @inlinable public init?(_ idx: String.Index, within target: String.UTF8View) { if _slowPath(target._guts.isForeign) { guard idx._foreignIsWithin(target) else { return nil } } else { // All indices, except sub-scalar UTF-16 indices pointing at trailing // surrogates, are valid. guard idx.transcodedOffset == 0 else { return nil } } self = idx } } // Reflection extension String.UTF8View : CustomReflectable { /// Returns a mirror that reflects the UTF-8 view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } //===--- Slicing Support --------------------------------------------------===// /// In Swift 3.2, in the absence of type context, /// /// someString.utf8[someString.utf8.startIndex..<someString.utf8.endIndex] /// /// was deduced to be of type `String.UTF8View`. Provide a more-specific /// Swift-3-only `subscript` overload that continues to produce /// `String.UTF8View`. extension String.UTF8View { public typealias SubSequence = Substring.UTF8View @inlinable @available(swift, introduced: 4) public subscript(r: Range<Index>) -> String.UTF8View.SubSequence { return Substring.UTF8View(self, _bounds: r) } } extension String.UTF8View { /// Copies `self` into the supplied buffer. /// /// - Precondition: The memory in `self` is uninitialized. The buffer must /// contain sufficient uninitialized memory to accommodate /// `source.underestimatedCount`. /// /// - Postcondition: The `Pointee`s at `buffer[startIndex..<returned index]` /// are initialized. @inlinable @inline(__always) public func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Iterator.Element> ) -> (Iterator, UnsafeMutableBufferPointer<Iterator.Element>.Index) { guard buffer.baseAddress != nil else { _preconditionFailure( "Attempt to copy string contents into nil buffer pointer") } guard let written = _guts.copyUTF8(into: buffer) else { _preconditionFailure( "Insufficient space allocated to copy string contents") } let it = String().utf8.makeIterator() return (it, buffer.index(buffer.startIndex, offsetBy: written)) } } // Foreign string support extension String.UTF8View { @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(after i: Index) -> Index { _internalInvariant(_guts.isForeign) let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar( startingAt: i.strippingTranscoding) let utf8Len = UTF8.width(scalar) if utf8Len == 1 { _internalInvariant(i.transcodedOffset == 0) return i.nextEncoded } // Check if we're still transcoding sub-scalar if i.transcodedOffset < utf8Len - 1 { return i.nextTranscoded } // Skip to the next scalar return i.encoded(offsetBy: scalarLen) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(before i: Index) -> Index { _internalInvariant(_guts.isForeign) if i.transcodedOffset != 0 { _internalInvariant((1...3) ~= i.transcodedOffset) return i.priorTranscoded } let (scalar, scalarLen) = _guts.foreignErrorCorrectedScalar( endingAt: i) let utf8Len = UTF8.width(scalar) return i.encoded(offsetBy: -scalarLen).transcoded(withOffset: utf8Len &- 1) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignSubscript(position i: Index) -> UTF8.CodeUnit { _internalInvariant(_guts.isForeign) let scalar = _guts.foreignErrorCorrectedScalar( startingAt: _guts.scalarAlign(i)).0 let encoded = Unicode.UTF8.encode(scalar)._unsafelyUnwrappedUnchecked _internalInvariant(i.transcodedOffset < 1+encoded.count) return encoded[ encoded.index(encoded.startIndex, offsetBy: i.transcodedOffset)] } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex(_ i: Index, offsetBy n: Int) -> Index { _internalInvariant(_guts.isForeign) return _index(i, offsetBy: n) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignIndex( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { _internalInvariant(_guts.isForeign) return _index(i, offsetBy: n, limitedBy: limit) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignDistance(from i: Index, to j: Index) -> Int { _internalInvariant(_guts.isForeign) #if _runtime(_ObjC) // Currently, foreign means NSString if let count = _cocoaStringUTF8Count( _guts._object.cocoaObject, range: i._encodedOffset ..< j._encodedOffset ) { //_cocoaStringUTF8Count gave us the scalar aligned count, but we still //need to compensate for sub-scalar indexing, e.g. if `i` is in the middle //of a two-byte UTF8 scalar. let refinedCount = count - (i.transcodedOffset + j.transcodedOffset) _internalInvariant(refinedCount == _distance(from: i, to: j)) return refinedCount } #endif return _distance(from: i, to: j) } @usableFromInline @inline(never) @_effects(releasenone) internal func _foreignCount() -> Int { _internalInvariant(_guts.isForeign) return _foreignDistance(from: startIndex, to: endIndex) } } extension String.Index { @usableFromInline @inline(never) // opaque slow-path @_effects(releasenone) internal func _foreignIsWithin(_ target: String.UTF8View) -> Bool { _internalInvariant(target._guts.isForeign) // Currently, foreign means UTF-16. // If we're transcoding, we're already a UTF8 view index. if self.transcodedOffset != 0 { return true } // Otherwise, we must be scalar-aligned, i.e. not pointing at a trailing // surrogate. return target._guts.isOnUnicodeScalarBoundary(self) } } extension String.UTF8View { @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { guard _guts.isFastUTF8 else { return nil } return try _guts.withFastUTF8(body) } }
apache-2.0
0bf8f0dba8e42eb76132a5ca1581390e
31.457143
80
0.645188
4.002819
false
false
false
false
soapyigu/Swift30Projects
Project 05 - Artistry/Artistry/ArtistDetailViewController.swift
1
3570
/* * Copyright (c) 2016 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit class ArtistDetailViewController: UIViewController { var selectedArtist: Artist! let moreInfoText = "Select For More Info >" @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() title = selectedArtist.name tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 300 NotificationCenter.default.addObserver(forName: UIContentSizeCategory.didChangeNotification, object: .none, queue: OperationQueue.main) { [weak self] _ in self?.tableView.reloadData() } } } extension ArtistDetailViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return selectedArtist.works.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! WorkTableViewCell let work = selectedArtist.works[indexPath.row] cell.workTitleLabel.text = work.title cell.workImageView.image = work.image cell.workTitleLabel.backgroundColor = UIColor(white: 204/255, alpha: 1) cell.workTitleLabel.textAlignment = .center cell.moreInfoTextView.textColor = UIColor(white: 114 / 255, alpha: 1) cell.selectionStyle = .none cell.moreInfoTextView.text = work.isExpanded ? work.info : moreInfoText cell.moreInfoTextView.textAlignment = work.isExpanded ? .left : .center cell.workTitleLabel.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.headline) cell.moreInfoTextView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.footnote) return cell } } extension ArtistDetailViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) as? WorkTableViewCell else { return } var work = selectedArtist.works[indexPath.row] work.isExpanded = !work.isExpanded selectedArtist.works[indexPath.row] = work cell.moreInfoTextView.text = work.isExpanded ? work.info : moreInfoText cell.moreInfoTextView.textAlignment = work.isExpanded ? .left : .center tableView.beginUpdates() tableView.endUpdates() tableView.scrollToRow(at: indexPath, at: .top, animated: true) } }
apache-2.0
a4bf502aaa9e078d44ded4ba795b25fb
36.578947
158
0.741176
4.734748
false
false
false
false
grigaci/RateMyTalkAtMobOS
RateMyTalkAtMobOS/Classes/Model/Entities+CloudKit/RMTSession+CloudKit.swift
1
2069
// // RMTSession+CloudKit.swift // RateMyTalkAtMobOSMaster // // Created by Bogdan Iusco on 10/4/14. // Copyright (c) 2014 Grigaci. All rights reserved. // import Foundation import CloudKit enum RMTSessionCKAttributes: NSString { case title = "title" case startDate = "startDate" case endDate = "endDate" } enum RMTSessionCKRelations: NSString { case speaker = "speaker" } extension RMTSession { class var ckRecordName: NSString { get { return "RMTSession"} } class func create(record: CKRecord, managedObjectContext: NSManagedObjectContext) -> RMTSession { let session: RMTSession = RMTSession(entity: RMTSession.entity(managedObjectContext), insertIntoManagedObjectContext: managedObjectContext) session.ckRecordID = record.recordID.recordName let title = record.valueForKey(RMTSessionCKAttributes.title.rawValue) as? NSString session.title = title let startDate = record.valueForKey(RMTSessionCKAttributes.startDate.rawValue) as? NSDate session.startDate = startDate let endDate = record.valueForKey(RMTSessionCKAttributes.endDate.rawValue) as? NSDate session.endDate = endDate let sessionToSpeakerReference = record.objectForKey(RMTSessionCKRelations.speaker.rawValue) as? CKReference if sessionToSpeakerReference != nil { let speakerRecordID = sessionToSpeakerReference?.recordID.recordName let speaker = RMTSpeaker.speakerWithRecordID(speakerRecordID!, managedObjectContext: managedObjectContext) session.speaker = speaker } return session; } class func sessionWithRecordID(recordID: NSString, managedObjectContext: NSManagedObjectContext) -> RMTSession? { let predicate = NSPredicate(format: "%K == %@", RMTCloudKitAttributes.ckRecordID.rawValue, recordID) let existingObject = RMTSession.MR_findFirstWithPredicate(predicate, inContext: managedObjectContext) as? RMTSession return existingObject } }
bsd-3-clause
2faf9971d8e18a0f81801958e3186336
34.067797
147
0.714838
4.937947
false
false
false
false
cweatureapps/SwiftScraper
Pods/Observable-Swift/Observable-Swift/Event.swift
2
2841
// // Event.swift // Observable-Swift // // Created by Leszek Ślażyński on 21/06/14. // Copyright (c) 2014 Leszek Ślażyński. All rights reserved. // // Events are implemented as structs, what has both advantages and disadvantages // Notably they are copied when inside other value types, and mutated on add/remove/notify // If you require a reference type for Event, use EventReference<T> instead /// A struct representing a collection of subscriptions with means to add, remove and notify them. public struct Event<T>: UnownableEvent { public typealias ValueType = T public typealias SubscriptionType = EventSubscription<T> public typealias HandlerType = SubscriptionType.HandlerType public private(set) var subscriptions = [SubscriptionType]() public init() { } public mutating func notify(_ value: T) { subscriptions = subscriptions.filter { $0.valid() } for subscription in subscriptions { subscription.handler(value) } } @discardableResult public mutating func add(_ subscription: SubscriptionType) -> SubscriptionType { subscriptions.append(subscription) return subscription } @discardableResult public mutating func add(_ handler: @escaping HandlerType) -> SubscriptionType { return add(SubscriptionType(owner: nil, handler: handler)) } public mutating func remove(_ subscription: SubscriptionType) { var newsubscriptions = [SubscriptionType]() var first = true for existing in subscriptions { if first && existing === subscription { first = false } else { newsubscriptions.append(existing) } } subscriptions = newsubscriptions } public mutating func removeAll() { subscriptions.removeAll() } @discardableResult public mutating func add(owner: AnyObject, _ handler: @escaping HandlerType) -> SubscriptionType { return add(SubscriptionType(owner: owner, handler: handler)) } public mutating func unshare() { // _subscriptions.unshare() } } @discardableResult public func += <T: UnownableEvent> (event: inout T, handler: @escaping (T.ValueType) -> ()) -> EventSubscription<T.ValueType> { return event.add(handler) } @discardableResult public func += <T: OwnableEvent> (event: T, handler: @escaping (T.ValueType) -> ()) -> EventSubscription<T.ValueType> { var e = event return e.add(handler) } public func -= <T: UnownableEvent> (event: inout T, subscription: EventSubscription<T.ValueType>) { return event.remove(subscription) } public func -= <T: OwnableEvent> (event: T, subscription: EventSubscription<T.ValueType>) { var e = event return e.remove(subscription) }
mit
7b021fe2e15ed28deabb1a635c18b9fc
31.586207
127
0.667725
4.655172
false
false
false
false
thankmelater23/MyFitZ
MyFitZ/AwesomeDataDemoAPI.swift
1
1118
// // AwesomeDataDemoAPI.swift // AwesomeData // // Created by Evandro Harrison Hoffmann on 27/08/2016. // Copyright © 2016 It's Day Off. All rights reserved. // import UIKit import AwesomeData class AwesomeDataDemoAPI: NSObject { static let unsplashListUrl = "https://unsplash.it/list" static func fetchUnsplashImages(_ success:@escaping (_ unsplashImages: [UnsplashImage])->Void, failure:@escaping (_ message: String?)->Void){ _ = AwesomeRequester.performRequest(unsplashListUrl, method: .GET) { (data) in if let jsonObject = AwesomeParser.jsonObject(data) { let unsplashImages = UnsplashImage.parseJSONArray(jsonObject) UnsplashImage.save() success(unsplashImages) }else{ if let data = data { if let message = String(data: data,encoding: String.Encoding.utf8) { failure(message) }else{ failure("Error parsing data") } } } } } }
mit
9b4a3471b1faefc12cfc32ffaeff416f
30.914286
145
0.56222
4.654167
false
false
false
false
evermeer/EVWordPressAPI
EVWordPressAPI/EVWordPressAPI_Sites.swift
1
6914
// // EVWordPressAPI_Sites.swift // EVWordPressAPI // // Created by Edwin Vermeer on 7/30/15. // Copyright (c) 2015 evict. All rights reserved. // import Alamofire import AlamofireOauth2 import AlamofireJsonToObjects import EVReflection public extension EVWordPressAPI { // MARK: - Sites /** Get information about a site. See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/ :param: parameters an array of siteParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Site object :return: No return value */ public func site(_ parameters:[basicParameters]? = nil, completionHandler: @escaping (Site?) -> Void) { genericCall("/sites/\(self.site)", parameters: parameters, completionHandler: completionHandler) } /** Get page templates for a site See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/page-templates/ :parameter: parameters: an array of basicParameters. For a complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Template object */ public func pageTemplates(_ parameters:[basicParameters]? = nil, completionHandler: @escaping (Templates?) -> Void) { genericCall("/sites/\(self.site)/page-templates", parameters: parameters, completionHandler: completionHandler) } /** Get the available shortcodes for a site See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/shortcodes/ :param: parameters an array of shortcodesParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Shortcodes object */ public func shortcodes(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Shortcodes?) -> Void) { genericOauthCall(.Shortcodes(pdict(parameters)), completionHandler: completionHandler) } /** Get the render for a shortcode See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/shortcodes/render/ :param: parameters an array of shortcodesRenderParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the ShortcodeRender object */ public func shortcodesRender(_ parameters:[shortcodesRenderParameters]? = nil, completionHandler: @escaping (ShortcodesRender?) -> Void) { genericOauthCall(.ShortcodesRender(pdict(parameters)), completionHandler: completionHandler) } /** Get the list of embeds See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/embeds/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Embeds object */ public func embeds(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Embeds?) -> Void) { genericOauthCall(.Embeds(pdict(parameters)), completionHandler: completionHandler) } /** Get an embeds render See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/embeds/render/ :param: parameters an array of embedsRenderParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the EmbedsRender object */ public func embedsRender(_ parameters:[embedsRenderParameters]? = nil, completionHandler: @escaping (EmbedsRender?) -> Void) { genericOauthCall(.EmbedsRender(pdict(parameters)), completionHandler: completionHandler) } /** Get a list of the current user's sites. See: https://developer.wordpress.com/docs/api/1.1/get/me/sites/ :param: parameters an array of basicContextParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Embeds object */ public func meSites(_ parameters:[meSitesParameters]? = nil, completionHandler: @escaping (Sites?) -> Void) { genericOauthCall(.MeSites(pdict(parameters)), completionHandler: completionHandler) } /** Get the list of widgets See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/widgets/ :param: parameters an array of basicParameters. For complete list plus documentation see the api documentation :param: completionHandler A code block that will be called with the Widgets object */ public func widgets(_ parameters:[basicParameters]? = nil, completionHandler: @escaping (Widgets?) -> Void) { genericCall("/sites/\(self.site)/widgets", parameters: parameters, completionHandler: completionHandler) } /** Get the settings of a widget See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/widgets/widget:%24id/ :param: id A specific widget id. :param: parameters an array of basicParameters. For complete list plus documentation see the api documentation. :param: completionHandler A code block that will be called with the Widgets object */ public func widget(id:String, parameters:[basicParameters]? = nil, completionHandler: @escaping (Widget?) -> Void) { genericCall("/sites/\(self.site)/widgets/widget:\(id)", parameters: parameters, completionHandler: completionHandler) } /** Get the custom header options for a site with a particular theme. See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/headers/%24theme_slug/ :param: themeSlug: The slug of the theme :param: parameters an array of basicParameters. For complete list plus documentation see the api documentation. :param: completionHandler A code block that will be called with the Widgets object */ public func headersForTheme(themeSlug:String, parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Header?) -> Void) { genericCall("/sites/\(self.site)/headers/\(themeSlug)", parameters: parameters, completionHandler: completionHandler) } /** Get the custom header options for a site. See: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/headers/mine/ :param: parameters an array of basicParameters. For complete list plus documentation see the api documentation. :param: completionHandler A code block that will be called with the Widgets object */ public func headers(_ parameters:[basicContextParameters]? = nil, completionHandler: @escaping (Header?) -> Void) { genericCall("/sites/\(self.site)/headers/mine", parameters: parameters, completionHandler: completionHandler) } }
bsd-3-clause
2d647f1f7791aaafc3cad8907a583df0
47.013889
143
0.723315
4.527832
false
false
false
false
kandelvijaya/XcodeFormatter
XcodeFormatter/Core/CodeAnalyzer/EmptyLineCorrection.swift
1
5544
// EmptyLineCorrection.swift // Copyright © 2016 Vijaya Prakash Kandel. All rights reserved. // import Foundation enum CodeDirection { case down, up, both } class EmptyLineCorrection { typealias CodePositonToCorrect = (CodePosition, CodeDirection) private let mutableContent: NSMutableArray private var codePositionsToCorrect: [CodePositonToCorrect] = [] private var offset = 0 private var currentLineIndex = 0 /// Create a EmptyLineCorrection Object that can correct empty lines /// /// - parameter mutableContent: Array of strings init(mutableContent: NSMutableArray) { self.mutableContent = mutableContent } /// Add code positions where empty lines should be added or removed /// depending on the direction parameter that is passed. Provided /// codePositos will be sorted in ascending order before correction. /// Calling this method multiple times will add the unique values /// and apply the correction. /// NOTE: 2 code positions with same lineIndex but different section/column /// values will not add/remove 2 lines. It just adds the work. /// /// - parameter codePositons: [CodePosition] /// - parameter direction: CodeDirection. which direction to correct. func add(codePositons: [CodePosition], withDirectionToCorrect direction: CodeDirection) { let newPosition = codePositons.map{ ($0, direction) } codePositionsToCorrect.append(contentsOf: newPosition) } func correct() { codePositionsToCorrect.sorted { (cp1, cp2) -> Bool in return cp1.0.line < cp2.0.line } .forEach { pos in if pos.1 == .both { correctEmptySpaceAbove(position: pos.0) correctEmptySpaceBelow(position: pos.0) } else if pos.1 == .up { correctEmptySpaceAbove(position: pos.0) } else if pos.1 == .down { correctEmptySpaceAbove(position: pos.0) } } } //TODO: Refactor these 2 algorithms into a simplified model private func correctEmptySpaceAbove(position: CodePosition) { let currentSearchLineIndex = correctedLineIndex(for: position) - 1 //looking upwards let indexToInsertEmptyLine = correctedLineIndex(for: position) var indicesOfEmptyLines = [Int]() var indicesOfCommentLines = [Int]() //When the code block starts the file. if currentSearchLineIndex < 0 { addEmptySpace(at: 0) return } for index in stride(from: currentSearchLineIndex, to: -1, by: -1) { if isEmpty(line: mutableContent[index] as! String) { indicesOfEmptyLines.append(index) }else if (mutableContent[index] as! String).isInsideComment() { //If we encountered emptyLines before finding comments then stop this loop if indicesOfEmptyLines.count > 0 { break }else { indicesOfCommentLines.append(index) continue } }else { break } } if indicesOfEmptyLines.count == 0 { addEmptySpace(at: indexToInsertEmptyLine - indicesOfCommentLines.count) } else if indicesOfEmptyLines.count == 1{ return } else { removeAllEmptySpace(atIndices: indicesOfEmptyLines) addEmptySpace(at: correctedLineIndex(for: position)) } } private func correctEmptySpaceBelow(position: CodePosition) { var currentSearchLineIndex = correctedLineIndex(for: position) + 1 //looking downwards var indicesOfEmptyLines = [Int]() //Weired calculation of 14 billion indexes //When there is no EOF empty line then add one and return guard currentSearchLineIndex < mutableContent.count else { mutableContent.add("\n") return } while isEmpty(line: mutableContent[currentSearchLineIndex] as! String) { //TODO: match for whitespace []*\n$ indicesOfEmptyLines.append(currentSearchLineIndex) if currentSearchLineIndex == mutableContent.count - 1 { break } else { currentSearchLineIndex += 1 } } if indicesOfEmptyLines.count == 0 { addEmptySpace(at: correctedLineIndex(for: position) + 1) } else if indicesOfEmptyLines.count == 1{ return } else { removeAllEmptySpace(atIndices: indicesOfEmptyLines) //using correctedPosition is wrong here addEmptySpace(at: indicesOfEmptyLines[0]) } } private func correctedLineIndex(for position: CodePosition) -> Int { return position.line + offset } private func addEmptySpace(at index: Int) { offset += 1 mutableContent.insert("\n", at: index) } private func removeAllEmptySpace(atIndices indices: [Int]) { offset += -indices.count //Removing indices.first or every index is a error index out of bound. indices.forEach { _ in mutableContent.removeObject(at: indices.min()! ) } } private func isEmpty(line: String) -> Bool { let trimmedLine = line.trimmingCharacters(in: CharacterSet(charactersIn: " ")) return trimmedLine == "\n" } }
mit
a05e3eb377dbaa59291113b0e65c6391
36.452703
116
0.612123
4.870826
false
false
false
false
mumbler/PReVo-iOS
ReVoModeloj/Komunaj/Modeloj/Lingvo.swift
1
1772
// // Lingvo.swift // PoshReVo // // Created by Robin Hill on 5/4/20. // Copyright © 2020 Robin Hill. All rights reserved. // import Foundation /* Reprezentas lingvon ekzistantan en la vortaro. Uzata en serĉado kaj listigado de tradukoj en artikoloj. */ public final class Lingvo : NSObject, NSSecureCoding { public let kodo: String public let nomo: String public init(kodo: String, nomo: String) { self.kodo = kodo self.nomo = nomo } // MARK: - NSSecureCoding public static var supportsSecureCoding = true public required convenience init?(coder aDecoder: NSCoder) { if let enkodo = aDecoder.decodeObject(forKey: "kodo") as? String, let ennomo = aDecoder.decodeObject(forKey: "nomo") as? String { self.init(kodo: enkodo, nomo: ennomo) } else { return nil } } public func encode(with aCoder: NSCoder) { aCoder.encode(kodo, forKey: "kodo") aCoder.encode(nomo, forKey: "nomo") } public override var hash: Int { return kodo.hashValue } } // MARK: - Equatable extension Lingvo { public override func isEqual(_ object: Any?) -> Bool { if let lingvo = object as? Lingvo { return self == lingvo } else { return false } } public static func ==(lhs: Lingvo, rhs: Lingvo) -> Bool { return lhs.kodo == rhs.kodo && lhs.nomo == rhs.nomo } } // MARK: - Comparable extension Lingvo: Comparable { public static func < (lhs: Lingvo, rhs: Lingvo) -> Bool { return lhs.nomo.compare(rhs.nomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending } }
mit
e5ad485f510a47897d66ee9541467391
23.583333
135
0.59887
3.89011
false
false
false
false
tbointeractive/TBODeveloperOverlay
Examples/TBODeveloperOverlay Example iOS/TBODeveloperOverlay Example iOS/AppDelegate.swift
1
3968
// // AppDelegate.swift // TBODeveloperOverlay Example iOS // // Created by Cornelius Horstmann on 28.07.17. // Copyright © 2017 TBO Interactive GmbH & CO KG. All rights reserved. // import UIKit import TBODeveloperOverlay @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UserDefaults.standard.set(Date(), forKey: "lastAppStart") UserDefaults.standard.set(true, forKey: "appHasBeenStarted") UserDefaults.standard.set("simple string", forKey: "simpleString") UserDefaults.standard.set(NSNumber(value: 12.3), forKey: "Number") UserDefaults.standard.set(12, forKey: "Int") writeExampleFile() window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UINavigationController(rootViewController: rootViewController()) window?.makeKeyAndVisible() return true } func writeExampleFile() { if let dir = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first { let path = dir.appendingPathComponent("example.txt") try? "Example Text".write(to: path, atomically: false, encoding: .utf8) } } func rootViewController() -> UIViewController { let viewController = TableViewController(style: .grouped, sections: [ Section(items: [ Section.Item.info(title: "Info without detail text", detail: nil), Section.Item.info(title: "Info without detail text but with a very very long title", detail: nil), Section.Item.info(title: "Info", detail: "with simple detail text"), Section.Item.info(title: "Info", detail: "with a long detail text, that shows how the cell behaves if the text is a little longer.") ], title: "Information"), Section(items: [ Section.Item.segue(title: "User Defaults", detail: "read only User Defaults Debugger", identifier: nil) { return UserDefaultsTableViewController(style: .grouped, userDefaults: UserDefaults.standard) }, Section.Item.segue(title: "User Defaults", detail: "editable User Defaults Debugger", identifier: nil) { return UserDefaultsTableViewController(style: .grouped, userDefaults: UserDefaults.standard, canEdit: true) }, Section.Item.segue(title: "User Defaults", detail: "read only with custom filter", identifier: nil) { return UserDefaultsTableViewController(style: .grouped, userDefaults: UserDefaults.standard, userDefaultsKeyFilter: { return $0.range(of: "Apple") == nil }) }, Section.Item.segue(title: "Custom ViewController", detail: "Displays a Custom ViewController", identifier: nil) { return UIViewController() }, Section.Item.segue(title: "File Inspector", detail: "", identifier: nil) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let url = URL(fileURLWithPath: documentsPath).deletingLastPathComponent() return FileListTableViewController(style: .grouped, basePath: url) } ], title: "Plugins"), Section(items: [ Section.Item.action(title: "Reset", detail: "Sets a reset Date to now", identifier: nil) { UserDefaults.standard.set(Date(), forKey: "lastReset") } ], title: "Actions") ], isSearchEnabled: false) viewController.title = "Developer Overlay" return viewController } }
mit
06630fe6a3e620e0853049d56a01c43e
50.519481
148
0.623645
5.145266
false
false
false
false
liuchuo/Swift-practice
20150727-3.playground/Contents.swift
1
776
//: Playground - noun: a place where people can play import UIKit class Employee { var no : Int = 0 var name : String = "Tony" { willSet(newNameValue) { println("员工name新值:\(newNameValue)") } didSet(oldNameValue) { println("员工name旧值:\(oldNameValue)") } } var job : String? var salary : Double = 0 var dept : Department? } struct Department { var no : Int = 10 { willSet { println("部门编号新值\(newValue)") } didSet { println("部门编号旧值\(oldValue)") } } var name : String = "RESEARCH" } var emp = Employee() emp.no = 100 emp.name = "smith" var dept = Department() dept.no = 30
gpl-2.0
8160c0b253fb3f75fea6ba2b76fc1cf0
16.853659
52
0.525956
3.66
false
false
false
false
jedlewison/AsyncOpKit
Tests/AsyncOpTests/AsyncOpPreconditionEvaluatorTests.swift
1
10007
// // AsyncOpPreconditionEvaluatorTests.swift // AsyncOp // // Created by Jed Lewison on 9/6/15. // Copyright © 2015 Magic App Factory. All rights reserved. // import Foundation import Quick import Nimble @testable import AsyncOpKit class AsyncOpPreconditionEvaluatorTests : QuickSpec { override func spec() { var randomOutputNumber = 0 var subject: AsyncOp<AsyncVoid, Int>? var opQ: NSOperationQueue? describe("Precondition Evaluator") { beforeEach { randomOutputNumber = random() subject = AsyncOp() subject?.onStart { op in op.finish(with: randomOutputNumber) } opQ = NSOperationQueue() } afterEach { subject = nil opQ = nil } describe("Single precondition scenarios") { context("evaluator that instructs operation to continue") { beforeEach { subject?.addPreconditionEvaluator { return .Continue } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the subject should finish normally") { expect(subject?.output.value).toEventually(equal(randomOutputNumber)) } } context("evaluator that instructs operation to cancel") { beforeEach { subject?.addPreconditionEvaluator { return .Cancel } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the subject should be a cancelled operation") { expect(subject?.cancelled).toEventually(beTrue()) } it("the subject should be cancelled") { expect(subject?.output.noneError?.cancelled).toEventually(beTrue()) } } context("evaluator that instructs operation to fail") { beforeEach { subject?.addPreconditionEvaluator { return .Fail(AsyncOpError.PreconditionFailure) } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the subject should be a cancelled operation") { expect(subject?.cancelled).toEventually(beTrue()) } it("the subject should be a failed asyncop") { expect(subject?.output.noneError?.failed).toEventually(beTrue()) } it("the subject shouldhave the same error that it was failed with") { expect(subject?.output.noneError?.failureError?._code).toEventually(equal(AsyncOpError.PreconditionFailure._code)) } } } describe("Multiple precondition scenarios") { context("multiple evaluators that instruct operation to continue") { beforeEach { subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the subject should finish normally") { expect(subject?.output.value).toEventually(equal(randomOutputNumber)) } } } context("multiple evaluators that instruct operation to continue, but one instructs canceling") { beforeEach { subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Cancel } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the subject should be a cancelled operation") { expect(subject?.cancelled).toEventually(beTrue()) } it("the subject should be cancelled") { expect(subject?.output.noneError?.cancelled).toEventually(beTrue()) } } context("multiple evaluators that instruct operation to continue, but one instructs Failing") { beforeEach { subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Fail(AsyncOpError.PreconditionFailure) } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the subject should be a cancelled operation") { expect(subject?.cancelled).toEventually(beTrue()) } it("the subject should be a failed asyncop") { expect(subject?.output.noneError?.failed).toEventually(beTrue()) } it("the subject shouldhave the same error that it was failed with") { expect(subject?.output.noneError?.failureError?._code).toEventually(equal(AsyncOpError.PreconditionFailure._code)) } } context("multiple evaluators that instruct operation to continue, but one instructs canceling and one instructs Failing") { beforeEach { subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Cancel } subject?.addPreconditionEvaluator { return .Fail(AsyncOpError.PreconditionFailure) } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the subject should be a cancelled operation") { expect(subject?.cancelled).toEventually(beTrue()) } it("the subject should be a failed asyncop") { expect(subject?.output.noneError?.failed).toEventually(beTrue()) } it("the subject shouldhave the same error that it was failed with") { expect(subject?.output.noneError?.failureError?._code).toEventually(equal(AsyncOpError.PreconditionFailure._code)) } } context("multiple evaluators that instruct operation to continue, but one instructs canceling and multiple instruct Failing") { beforeEach { subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Continue } subject?.addPreconditionEvaluator { return .Cancel } subject?.addPreconditionEvaluator { return .Fail(AsyncOpError.PreconditionFailure) } subject?.addPreconditionEvaluator { return .Fail(AsyncOpError.PreconditionFailure) } subject?.addPreconditionEvaluator { return .Fail(AsyncOpError.PreconditionFailure) } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the subject should be a cancelled operation") { expect(subject?.cancelled).toEventually(beTrue()) } it("the subject should be a failed asyncop") { expect(subject?.output.noneError?.failed).toEventually(beTrue()) } } } } }
mit
4bb8465b1ce93c20c6f92a7490b7b4cd
35.922509
139
0.46712
6.929363
false
false
false
false
apple/swift-driver
Tests/SwiftDriverTests/JobExecutorTests.swift
1
25250
//===--------------- JobExecutorTests.swift - Swift Execution Tests -------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 XCTest import TSCBasic @_spi(Testing) import SwiftDriver import SwiftDriverExecution import TestUtilities extension Job.ArgTemplate: ExpressibleByStringLiteral { public init(stringLiteral value: String) { self = .flag(value) } } class JobCollectingDelegate: JobExecutionDelegate { struct StubProcess: ProcessProtocol { static func launchProcess(arguments: [String], env: [String : String]) throws -> StubProcess { return .init() } static func launchProcessAndWriteInput(arguments: [String], env: [String : String], inputFileHandle: FileHandle) throws -> StubProcess { return .init() } var processID: TSCBasic.Process.ProcessID { .init(-1) } func waitUntilExit() throws -> ProcessResult { return ProcessResult( arguments: [], environment: [:], exitStatus: .terminated(code: EXIT_SUCCESS), output: Result.success(ByteString("test").contents), stderrOutput: Result.success([]) ) } } var started: [Job] = [] var finished: [(Job, ProcessResult)] = [] func jobFinished(job: Job, result: ProcessResult, pid: Int) { finished.append((job, result)) } func jobStarted(job: Job, arguments: [String], pid: Int) { started.append(job) } func jobSkipped(job: Job) {} } extension DarwinToolchain { /// macOS SDK path, for testing only. var sdk: Result<AbsolutePath, Swift.Error> { Result { let result = try executor.checkNonZeroExit( args: "xcrun", "-sdk", "macosx", "--show-sdk-path", environment: env ).spm_chomp() return AbsolutePath(result) } } /// macOS resource directory, for testing only. var resourcesDirectory: Result<AbsolutePath, Swift.Error> { return Result { try AbsolutePath("../../lib/swift/macosx", relativeTo: getToolPath(.swiftCompiler)) } } var clangRT: Result<AbsolutePath, Error> { resourcesDirectory.map { AbsolutePath("../clang/lib/darwin/libclang_rt.osx.a", relativeTo: $0) } } var compatibility50: Result<AbsolutePath, Error> { resourcesDirectory.map { $0.appending(component: "libswiftCompatibility50.a") } } var compatibilityDynamicReplacements: Result<AbsolutePath, Error> { resourcesDirectory.map { $0.appending(component: "libswiftCompatibilityDynamicReplacements.a") } } } final class JobExecutorTests: XCTestCase { func testDarwinBasic() throws { #if os(macOS) let hostTriple = try Driver(args: ["swiftc", "test.swift"]).hostTriple let executor = try SwiftDriverExecutor(diagnosticsEngine: DiagnosticsEngine(), processSet: ProcessSet(), fileSystem: localFileSystem, env: ProcessEnv.vars) let toolchain = DarwinToolchain(env: ProcessEnv.vars, executor: executor) try withTemporaryDirectory { path in let foo = path.appending(component: "foo.swift") let main = path.appending(component: "main.swift") try localFileSystem.writeFileContents(foo) { $0 <<< "let foo = 5" } try localFileSystem.writeFileContents(main) { $0 <<< "print(foo)" } let exec = path.appending(component: "main") let resolver = try ArgsResolver(fileSystem: localFileSystem) resolver.pathMapping = [ .relative(RelativePath("foo.swift")): foo.pathString, .relative(RelativePath("main.swift")): main.pathString, .relative(RelativePath("main")): exec.pathString, ] let inputs: [String: TypedVirtualPath] = [ "foo" : .init(file: VirtualPath.relative(RelativePath( "foo.swift")).intern(), type: .swift), "main": .init(file: VirtualPath.relative(RelativePath("main.swift")).intern(), type: .swift) ] let compileFoo = Job( moduleName: "main", kind: .compile, tool: try toolchain.resolvedTool(.swiftCompiler), commandLine: [ "-frontend", "-c", "-primary-file", .path(inputs[ "foo"]!.file), .path(inputs["main"]!.file), "-target", .flag(hostTriple.triple), "-enable-objc-interop", "-sdk", .path(.absolute(try toolchain.sdk.get())), "-module-name", "main", "-o", .path(.temporary(RelativePath("foo.o"))), ], inputs: Array(inputs.values), primaryInputs: [inputs["foo"]!], outputs: [.init(file: VirtualPath.temporary(RelativePath("foo.o")).intern(), type: .object)] ) let compileMain = Job( moduleName: "main", kind: .compile, tool: try toolchain.resolvedTool(.swiftCompiler), commandLine: [ "-frontend", "-c", .path(.relative(RelativePath("foo.swift"))), "-primary-file", .path(inputs["main"]!.file), "-target", .flag(hostTriple.triple), "-enable-objc-interop", "-sdk", .path(.absolute(try toolchain.sdk.get())), "-module-name", "main", "-o", .path(.temporary(RelativePath("main.o"))), ], inputs: Array(inputs.values), primaryInputs: [inputs["main"]!], outputs: [.init(file: VirtualPath.temporary(RelativePath("main.o")).intern(), type: .object)] ) let link = Job( moduleName: "main", kind: .link, tool: try toolchain.resolvedTool(.dynamicLinker), commandLine: [ .path(.temporary(RelativePath("foo.o"))), .path(.temporary(RelativePath("main.o"))), .path(.absolute(try toolchain.clangRT.get())), "--sysroot", .path(.absolute(try toolchain.sdk.get())), "-lobjc", "-lSystem", .flag("--target=\(hostTriple.triple)"), "-L", .path(.absolute(try toolchain.resourcesDirectory.get())), "-L", .path(.absolute(try toolchain.sdkStdlib(sdk: toolchain.sdk.get()))), "-rpath", "/usr/lib/swift", "-o", .path(.relative(RelativePath("main"))), ], inputs: [ .init(file: VirtualPath.temporary(RelativePath("foo.o")).intern(), type: .object), .init(file: VirtualPath.temporary(RelativePath("main.o")).intern(), type: .object), ], primaryInputs: [], outputs: [.init(file: VirtualPath.relative(RelativePath("main")).intern(), type: .image)] ) let delegate = JobCollectingDelegate() let executor = MultiJobExecutor(workload: .all([compileFoo, compileMain, link]), resolver: resolver, executorDelegate: delegate, diagnosticsEngine: DiagnosticsEngine()) try executor.execute(env: toolchain.env, fileSystem: localFileSystem) let output = try TSCBasic.Process.checkNonZeroExit(args: exec.pathString) XCTAssertEqual(output, "5\n") XCTAssertEqual(delegate.started.count, 3) let fooObject = try resolver.resolve(.path(.temporary(RelativePath("foo.o")))) XCTAssertTrue(localFileSystem.exists(AbsolutePath(fooObject)), "expected foo.o to be present in the temporary directory") try resolver.removeTemporaryDirectory() XCTAssertFalse(localFileSystem.exists(AbsolutePath(fooObject)), "expected foo.o to be removed from the temporary directory") } #endif } /// Ensure the executor is capable of forwarding its standard input to the compile job that requires it. func testInputForwarding() throws { #if os(macOS) let hostTriple = try Driver(args: ["swiftc", "test.swift"]).hostTriple let executor = try SwiftDriverExecutor(diagnosticsEngine: DiagnosticsEngine(), processSet: ProcessSet(), fileSystem: localFileSystem, env: ProcessEnv.vars) let toolchain = DarwinToolchain(env: ProcessEnv.vars, executor: executor) try withTemporaryDirectory { path in let exec = path.appending(component: "main") let compile = Job( moduleName: "main", kind: .compile, tool: try toolchain.resolvedTool(.swiftCompiler), commandLine: [ "-frontend", "-c", "-primary-file", // This compile job must read the input from STDIN "-", "-target", .flag(hostTriple.triple), "-enable-objc-interop", "-sdk", .path(.absolute(try toolchain.sdk.get())), "-module-name", "main", "-o", .path(.temporary(RelativePath("main.o"))), ], inputs: [TypedVirtualPath(file: .standardInput, type: .swift )], primaryInputs: [TypedVirtualPath(file: .standardInput, type: .swift )], outputs: [.init(file: VirtualPath.temporary(RelativePath("main.o")).intern(), type: .object)] ) let link = Job( moduleName: "main", kind: .link, tool: try toolchain.resolvedTool(.dynamicLinker), commandLine: [ .path(.temporary(RelativePath("main.o"))), "--sysroot", .path(.absolute(try toolchain.sdk.get())), "-lobjc", "-lSystem", .flag("--target=\(hostTriple.triple)"), "-L", .path(.absolute(try toolchain.resourcesDirectory.get())), "-L", .path(.absolute(try toolchain.sdkStdlib(sdk: toolchain.sdk.get()))), "-o", .path(.absolute(exec)), ], inputs: [ .init(file: VirtualPath.temporary(RelativePath("main.o")).intern(), type: .object), ], primaryInputs: [], outputs: [.init(file: VirtualPath.relative(RelativePath("main")).intern(), type: .image)] ) // Create a file with inpuit let inputFile = path.appending(component: "main.swift") try localFileSystem.writeFileContents(inputFile) { $0 <<< "print(\"Hello, World\")" } // We are going to override he executors standard input FileHandle to the above // input file, to simulate it being piped over standard input to this compilation. let testFile: FileHandle = FileHandle(forReadingAtPath: inputFile.description)! let delegate = JobCollectingDelegate() let resolver = try ArgsResolver(fileSystem: localFileSystem) let executor = MultiJobExecutor(workload: .all([compile, link]), resolver: resolver, executorDelegate: delegate, diagnosticsEngine: DiagnosticsEngine(), inputHandleOverride: testFile) try executor.execute(env: toolchain.env, fileSystem: localFileSystem) // Execute the resulting program let output = try TSCBasic.Process.checkNonZeroExit(args: exec.pathString) XCTAssertEqual(output, "Hello, World\n") } #endif } func testStubProcessProtocol() throws { #if os(Windows) throw XCTSkip("processId.getter returning `-1`") #else let job = Job( moduleName: "main", kind: .compile, tool: ResolvedTool(path: AbsolutePath("/usr/bin/swift"), supportsResponseFiles: false), commandLine: [.flag("something")], inputs: [], primaryInputs: [], outputs: [.init(file: VirtualPath.temporary(RelativePath("main")).intern(), type: .object)] ) let delegate = JobCollectingDelegate() let executor = MultiJobExecutor( workload: .all([job]), resolver: try ArgsResolver(fileSystem: localFileSystem), executorDelegate: delegate, diagnosticsEngine: DiagnosticsEngine(), processType: JobCollectingDelegate.StubProcess.self ) try executor.execute(env: ProcessEnv.vars, fileSystem: localFileSystem) XCTAssertEqual(try delegate.finished[0].1.utf8Output(), "test") #endif } func testSwiftDriverExecOverride() throws { var env = ProcessEnv.vars let envVarName = "SWIFT_DRIVER_SWIFT_FRONTEND_EXEC" let dummyPath = "/some/garbage/path/fnord" let executor = try SwiftDriverExecutor(diagnosticsEngine: DiagnosticsEngine(), processSet: ProcessSet(), fileSystem: localFileSystem, env: env) // DarwinToolchain env.removeValue(forKey: envVarName) let normalSwiftPath = try DarwinToolchain(env: env, executor: executor).getToolPath(.swiftCompiler) // Match Toolchain temporary shim of a fallback to looking for "swift" before failing. XCTAssertTrue(normalSwiftPath.basenameWithoutExt == "swift-frontend" || normalSwiftPath.basenameWithoutExt == "swift") env[envVarName] = dummyPath let overriddenSwiftPath = try DarwinToolchain(env: env, executor: executor).getToolPath(.swiftCompiler) XCTAssertEqual(overriddenSwiftPath, AbsolutePath(dummyPath)) // GenericUnixToolchain env.removeValue(forKey: envVarName) let unixSwiftPath = try GenericUnixToolchain(env: env, executor: executor).getToolPath(.swiftCompiler) XCTAssertTrue(unixSwiftPath.basenameWithoutExt == "swift-frontend" || unixSwiftPath.basenameWithoutExt == "swift") env[envVarName] = dummyPath let unixOverriddenSwiftPath = try GenericUnixToolchain(env: env, executor: executor).getToolPath(.swiftCompiler) XCTAssertEqual(unixOverriddenSwiftPath, AbsolutePath(dummyPath)) } func testInputModifiedDuringSingleJobBuild() throws { #if os(Windows) throw XCTSkip("Requires -sdk") #else try withTemporaryDirectory { path in let main = path.appending(component: "main.swift") try localFileSystem.writeFileContents(main) { $0 <<< "let foo = 1" } var driver = try Driver(args: ["swift", main.pathString]) let jobs = try driver.planBuild() XCTAssertTrue(jobs.count == 1 && jobs[0].requiresInPlaceExecution) // Change the file try localFileSystem.writeFileContents(main) { $0 <<< "let foo = 1" } XCTAssertThrowsError(try driver.run(jobs: jobs)) { XCTAssertEqual($0 as? Job.InputError, .inputUnexpectedlyModified(TypedVirtualPath(file: VirtualPath.absolute(main).intern(), type: .swift))) } } #endif } func testShellEscapingArgsInJobDescription() throws { let executor = try SwiftDriverExecutor(diagnosticsEngine: DiagnosticsEngine(), processSet: ProcessSet(), fileSystem: localFileSystem, env: [:]) let job = Job(moduleName: "Module", kind: .compile, tool: ResolvedTool( path: AbsolutePath("/path/to/the tool"), supportsResponseFiles: false), commandLine: [.path(.absolute(.init("/with space"))), .path(.absolute(.init("/withoutspace")))], inputs: [], primaryInputs: [], outputs: []) #if os(Windows) XCTAssertEqual(try executor.description(of: job, forceResponseFiles: false), #""\path\to\the tool" "\with space" \withoutspace"#) #else XCTAssertEqual(try executor.description(of: job, forceResponseFiles: false), "'/path/to/the tool' '/with space' /withoutspace") #endif } func testInputModifiedDuringMultiJobBuild() throws { try withTemporaryDirectory { path in let main = path.appending(component: "main.swift") try localFileSystem.writeFileContents(main) { $0 <<< "let foo = 1" } let other = path.appending(component: "other.swift") try localFileSystem.writeFileContents(other) { $0 <<< "let bar = 2" } // Sleep for 1s to allow for quiescing mtimes on filesystems with // insufficient timestamp precision. Thread.sleep(forTimeInterval: 1) try assertDriverDiagnostics(args: ["swiftc", main.pathString, other.pathString]) {driver, verifier in let jobs = try driver.planBuild() XCTAssertTrue(jobs.count > 1) // Change the file try localFileSystem.writeFileContents(other) { $0 <<< "let bar = 3" } verifier.expect(.error("input file '\(other.description)' was modified during the build")) // There's a tool-specific linker error that usually happens here from // whatever job runs last - probably the linker. // It's no use testing for a particular error message, let's just make // sure we emit the diagnostic we need. verifier.permitUnexpected(.error) XCTAssertThrowsError(try driver.run(jobs: jobs)) } } } func testTemporaryFileWriting() throws { try withTemporaryDirectory { path in let resolver = try ArgsResolver(fileSystem: localFileSystem, temporaryDirectory: .absolute(path)) let tmpPath = VirtualPath.temporaryWithKnownContents(.init("one.txt"), "hello, world!".data(using: .utf8)!) let resolvedOnce = try resolver.resolve(.path(tmpPath)) let readContents = try localFileSystem.readFileContents(.init(validating: resolvedOnce)) XCTAssertEqual(readContents, "hello, world!") let resolvedTwice = try resolver.resolve(.path(tmpPath)) XCTAssertEqual(resolvedOnce, resolvedTwice) let readContents2 = try localFileSystem.readFileContents(.init(validating: resolvedTwice)) XCTAssertEqual(readContents2, readContents) } } func testResolveSquashedArgs() throws { try withTemporaryDirectory { path in let resolver = try ArgsResolver(fileSystem: localFileSystem, temporaryDirectory: .absolute(path)) let tmpPath = VirtualPath.temporaryWithKnownContents(.init("one.txt"), "hello, world!".data(using: .utf8)!) let tmpPath2 = VirtualPath.temporaryWithKnownContents(.init("two.txt"), "goodbye!".data(using: .utf8)!) let resolvedCommandLine = try resolver.resolve( .squashedArgumentList(option: "--opt=", args: [.path(tmpPath), .path(tmpPath2)])) XCTAssertEqual(resolvedCommandLine, "--opt=\(path.appending(component: "one.txt").pathString) \(path.appending(component: "two.txt").pathString)") #if os(Windows) XCTAssertEqual(resolvedCommandLine.spm_shellEscaped(), #""--opt=\#(path.appending(component: "one.txt").pathString) \#(path.appending(component: "two.txt").pathString)""#) #else XCTAssertEqual(resolvedCommandLine.spm_shellEscaped(), "'--opt=\(path.appending(component: "one.txt").pathString) \(path.appending(component: "two.txt").pathString)'") #endif } } private func getHostToolchainSdkArg(_ executor: SwiftDriverExecutor) throws -> [String] { #if os(macOS) let toolchain = DarwinToolchain(env: ProcessEnv.vars, executor: executor) return try ["-sdk", toolchain.sdk.get().pathString] #elseif os(Windows) let toolchain = WindowsToolchain(env: ProcessEnv.vars, executor: executor) if let path = try toolchain.defaultSDKPath(nil) { return ["-sdk", path.nativePathString(escaped: false)] } return [] #else return [] #endif } func testSaveTemps() throws { do { try withTemporaryDirectory { path in let main = path.appending(component: "main.swift") try localFileSystem.writeFileContents(main) { $0 <<< "print(\"hello, world!\")" } let diags = DiagnosticsEngine() let executor = try SwiftDriverExecutor(diagnosticsEngine: diags, processSet: ProcessSet(), fileSystem: localFileSystem, env: ProcessEnv.vars) let outputPath = path.appending(component: "finalOutput") var driver = try Driver(args: ["swiftc", main.pathString, "-driver-filelist-threshold", "0", "-o", outputPath.pathString] + getHostToolchainSdkArg(executor), env: ProcessEnv.vars, diagnosticsEngine: diags, fileSystem: localFileSystem, executor: executor) let jobs = try driver.planBuild() XCTAssertEqual(jobs.removingAutolinkExtractJobs().map(\.kind), [.compile, .link]) XCTAssertEqual(jobs[0].outputs.count, 1) let compileOutput = jobs[0].outputs[0].file guard matchTemporary(compileOutput, "main.o") else { XCTFail("unexpected output") return } try driver.run(jobs: jobs) XCTAssertTrue(localFileSystem.exists(outputPath)) // -save-temps wasn't passed, so ensure the temporary file was removed. XCTAssertFalse( localFileSystem.exists(.init(try executor.resolver.resolve(.path(driver.allSourcesFileList!)))) ) XCTAssertFalse(localFileSystem.exists(.init(try executor.resolver.resolve(.path(compileOutput))))) } } do { try withTemporaryDirectory { path in let main = path.appending(component: "main.swift") try localFileSystem.writeFileContents(main) { $0 <<< "print(\"hello, world!\")" } let diags = DiagnosticsEngine() let executor = try SwiftDriverExecutor(diagnosticsEngine: diags, processSet: ProcessSet(), fileSystem: localFileSystem, env: ProcessEnv.vars) let outputPath = path.appending(component: "finalOutput") var driver = try Driver(args: ["swiftc", main.pathString, "-save-temps", "-driver-filelist-threshold", "0", "-o", outputPath.pathString] + getHostToolchainSdkArg(executor), env: ProcessEnv.vars, diagnosticsEngine: diags, fileSystem: localFileSystem, executor: executor) let jobs = try driver.planBuild() XCTAssertEqual(jobs.removingAutolinkExtractJobs().map(\.kind), [.compile, .link]) XCTAssertEqual(jobs[0].outputs.count, 1) let compileOutput = jobs[0].outputs[0].file guard matchTemporary(compileOutput, "main.o") else { XCTFail("unexpected output") return } try driver.run(jobs: jobs) XCTAssertTrue(localFileSystem.exists(outputPath)) // -save-temps was passed, so ensure the temporary file was not removed. XCTAssertTrue( localFileSystem.exists(.init(try executor.resolver.resolve(.path(driver.allSourcesFileList!)))) ) XCTAssertTrue(localFileSystem.exists(.init(try executor.resolver.resolve(.path(compileOutput))))) } } do { try withTemporaryDirectory { path in let main = path.appending(component: "main.swift") try localFileSystem.writeFileContents(main) { $0 <<< "print(\"hello, world!\")" } let diags = DiagnosticsEngine() let executor = try SwiftDriverExecutor(diagnosticsEngine: diags, processSet: ProcessSet(), fileSystem: localFileSystem, env: ProcessEnv.vars) let outputPath = path.appending(component: "finalOutput") var driver = try Driver(args: ["swiftc", main.pathString, "-driver-filelist-threshold", "0", "-Xfrontend", "-debug-crash-immediately", "-o", outputPath.pathString] + getHostToolchainSdkArg(executor), env: ProcessEnv.vars, diagnosticsEngine: diags, fileSystem: localFileSystem, executor: executor) let jobs = try driver.planBuild() XCTAssertEqual(jobs.removingAutolinkExtractJobs().map(\.kind), [.compile, .link]) XCTAssertEqual(jobs[0].outputs.count, 1) let compileOutput = jobs[0].outputs[0].file guard matchTemporary(compileOutput, "main.o") else { XCTFail("unexpected output") return } try? driver.run(jobs: jobs) // A job crashed, so ensure any temporary files written so far are preserved. XCTAssertTrue( localFileSystem.exists(.init(try executor.resolver.resolve(.path(driver.allSourcesFileList!)))) ) } } } }
apache-2.0
d0cc76009f88f2eaca88adfa6e3db581
41.86927
173
0.606733
4.7516
false
false
false
false
alantsev/mal
swift3/Sources/step7_quote/main.swift
3
5990
import Foundation // read func READ(str: String) throws -> MalVal { return try read_str(str) } // eval func is_pair(ast: MalVal) -> Bool { switch ast { case MalVal.MalList(let lst, _): return lst.count > 0 case MalVal.MalVector(let lst, _): return lst.count > 0 default: return false } } func quasiquote(ast: MalVal) -> MalVal { if !is_pair(ast) { return list([MalVal.MalSymbol("quote"), ast]) } let a0 = try! _nth(ast, 0) switch a0 { case MalVal.MalSymbol("unquote"): return try! _nth(ast, 1) default: true // fallthrough } if is_pair(a0) { let a00 = try! _nth(a0, 0) switch a00 { case MalVal.MalSymbol("splice-unquote"): return list([MalVal.MalSymbol("concat"), try! _nth(a0, 1), quasiquote(try! rest(ast))]) default: true // fallthrough } } return list([MalVal.MalSymbol("cons"), quasiquote(a0), quasiquote(try! rest(ast))]) } func eval_ast(ast: MalVal, _ env: Env) throws -> MalVal { switch ast { case MalVal.MalSymbol: return try env.get(ast) case MalVal.MalList(let lst, _): return list(try lst.map { try EVAL($0, env) }) case MalVal.MalVector(let lst, _): return vector(try lst.map { try EVAL($0, env) }) case MalVal.MalHashMap(let dict, _): var new_dict = Dictionary<String,MalVal>() for (k,v) in dict { new_dict[k] = try EVAL(v, env) } return hash_map(new_dict) default: return ast } } func EVAL(orig_ast: MalVal, _ orig_env: Env) throws -> MalVal { var ast = orig_ast, env = orig_env while true { switch ast { case MalVal.MalList(let lst, _): if lst.count == 0 { return ast } default: return try eval_ast(ast, env) } switch ast { case MalVal.MalList(let lst, _): switch lst[0] { case MalVal.MalSymbol("def!"): return try env.set(lst[1], try EVAL(lst[2], env)) case MalVal.MalSymbol("let*"): let let_env = try Env(env) var binds = Array<MalVal>() switch lst[1] { case MalVal.MalList(let l, _): binds = l case MalVal.MalVector(let l, _): binds = l default: throw MalError.General(msg: "Invalid let* bindings") } var idx = binds.startIndex while idx < binds.endIndex { let v = try EVAL(binds[idx.successor()], let_env) try let_env.set(binds[idx], v) idx = idx.successor().successor() } env = let_env ast = lst[2] // TCO case MalVal.MalSymbol("quote"): return lst[1] case MalVal.MalSymbol("quasiquote"): ast = quasiquote(lst[1]) // TCO case MalVal.MalSymbol("do"): let slc = lst[1..<lst.endIndex.predecessor()] try eval_ast(list(Array(slc)), env) ast = lst[lst.endIndex.predecessor()] // TCO case MalVal.MalSymbol("if"): switch try EVAL(lst[1], env) { case MalVal.MalFalse, MalVal.MalNil: if lst.count > 3 { ast = lst[3] // TCO } else { return MalVal.MalNil } default: ast = lst[2] // TCO } case MalVal.MalSymbol("fn*"): return malfunc( { return try EVAL(lst[2], Env(env, binds: lst[1], exprs: list($0))) }, ast:[lst[2]], env:env, params:[lst[1]]) default: switch try eval_ast(ast, env) { case MalVal.MalList(let elst, _): switch elst[0] { case MalVal.MalFunc(let fn, nil, _, _, _, _): let args = Array(elst[1..<elst.count]) return try fn(args) case MalVal.MalFunc(_, let a, let e, let p, _, _): let args = Array(elst[1..<elst.count]) env = try Env(e, binds: p![0], exprs: list(args)) // TCO ast = a![0] // TCO default: throw MalError.General(msg: "Cannot apply on '\(elst[0])'") } default: throw MalError.General(msg: "Invalid apply") } } default: throw MalError.General(msg: "Invalid apply") } } } // print func PRINT(exp: MalVal) -> String { return pr_str(exp, true) } // repl func rep(str:String) throws -> String { return PRINT(try EVAL(try READ(str), repl_env)) } var repl_env: Env = try Env() // core.swift: defined using Swift for (k, fn) in core_ns { try repl_env.set(MalVal.MalSymbol(k), malfunc(fn)) } try repl_env.set(MalVal.MalSymbol("eval"), malfunc({ try EVAL($0[0], repl_env) })) let pargs = Process.arguments.map { MalVal.MalString($0) } // TODO: weird way to get empty list, fix this var args = pargs[pargs.startIndex..<pargs.startIndex] if pargs.startIndex.advancedBy(2) < pargs.endIndex { args = pargs[pargs.startIndex.advancedBy(2)..<pargs.endIndex] } try repl_env.set(MalVal.MalSymbol("*ARGV*"), list(Array(args))) // core.mal: defined using the language itself try rep("(def! not (fn* (a) (if a false true)))") try rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))") if Process.arguments.count > 1 { try rep("(load-file \"" + Process.arguments[1] + "\")") exit(0) } while true { print("user> ", terminator: "") let line = readLine(stripNewline: true) if line == nil { break } if line == "" { continue } do { print(try rep(line!)) } catch (MalError.Reader(let msg)) { print("Error: \(msg)") } catch (MalError.General(let msg)) { print("Error: \(msg)") } }
mpl-2.0
b873c135a4261cb0b0dd7fe0ce4f75c5
30.861702
89
0.517696
3.810433
false
false
false
false
practicalswift/swift
test/NameBinding/name_lookup_min_max_conditional_conformance.swift
7
2843
// RUN: %target-typecheck-verify-swift extension Range { func f(_ value: Bound) -> Bound { return max(lowerBound, min(value, upperBound)) // expected-warning@-1{{use of 'max' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'Range' which comes via a conditional conformance}} // expected-note@-2{{use 'Swift.' to continue to reference the global function}} // expected-warning@-3{{use of 'min' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'Range' which comes via a conditional conformance}} // expected-note@-4{{use 'Swift.' to continue to reference the global function}} } } protocol ContainsMinMax {} extension ContainsMinMax { func max() {} func min() {} } func foo(_: Int, _: Int) {} // expected-note@-1 {{'foo' declared here}} protocol ContainsFoo {} extension ContainsFoo { func foo() {} } struct NonConditional: ContainsMinMax, ContainsFoo {} extension NonConditional { func f() { _ = max(1, 2) // expected-error@-1{{use of 'max' refers to instance method}} // expected-note@-2{{use 'Swift.' to reference the global function}} _ = min(3, 4) // expected-error@-1{{use of 'min' refers to instance method}} // expected-note@-2{{use 'Swift.' to reference the global function}} _ = foo(5, 6) // expected-error@-1{{use of 'foo' refers to instance method}} // expected-note@-2{{use 'name_lookup_min_max_conditional_conformance.' to reference the global function}} } } struct Conditional<T> {} extension Conditional: ContainsMinMax where T: ContainsMinMax {} extension Conditional: ContainsFoo where T: ContainsFoo {} // expected-note {{requirement from conditional conformance of 'Conditional<T>' to 'ContainsFoo'}} extension Conditional { func f() { _ = max(1, 2) // expected-warning@-1{{use of 'max' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'Conditional' which comes via a conditional conformance}} // expected-note@-2{{use 'Swift.' to continue to reference the global function}} _ = min(3, 4) // expected-warning@-1{{use of 'min' as reference to global function in module 'Swift' will change in future versions of Swift to reference instance method in generic struct 'Conditional' which comes via a conditional conformance}} // expected-note@-2{{use 'Swift.' to continue to reference the global function}} _ = foo(5, 6) // expected-error@-1{{referencing instance method 'foo()' on 'Conditional' requires that 'T' conform to 'ContainsFoo'}} } }
apache-2.0
893e218dbf5943a097015c74eef07a35
48.017241
239
0.67886
4.23696
false
false
false
false
mpangburn/RayTracer
RayTracer/Models/Finish.swift
1
3406
// // Finish.swift // RayTracer // // Created by Michael Pangburn on 6/26/17. // Copyright © 2017 Michael Pangburn. All rights reserved. // import Foundation /// Describes how an object interacts with light. final class Finish: NSObject, NSCoding { /// The percentage of ambient light reflected by the finish. var ambient: Double /// The percentage of diffuse light reflected by the finish. var diffuse: Double /// The percentage of specular light reflected by the finish. var specular: Double /// The modeled roughness of the finish, which affects the spread of the specular light across the object. var roughness: Double /** Creates a finish with the attributes. - Parameters: - ambient: The percentage of ambient light reflected by the finish. - diffuse: The percentage of diffuse light reflected by the finish - specular: The percentage of specular light reflected by the finish. - roughness: The modeled roughness of the finish. */ init(ambient: Double, diffuse: Double, specular: Double, roughness: Double) { self.ambient = ambient self.diffuse = diffuse self.specular = specular self.roughness = roughness } // MARK: - NSCoding private enum CodingKey: String { case ambient, diffuse, specular, roughness } required convenience init?(coder aDecoder: NSCoder) { let ambient = aDecoder.decodeDouble(forKey: CodingKey.ambient.rawValue) let diffuse = aDecoder.decodeDouble(forKey: CodingKey.diffuse.rawValue) let specular = aDecoder.decodeDouble(forKey: CodingKey.specular.rawValue) let roughness = aDecoder.decodeDouble(forKey: CodingKey.roughness.rawValue) self.init(ambient: ambient, diffuse: diffuse, specular: specular, roughness: roughness) } func encode(with aCoder: NSCoder) { aCoder.encode(self.ambient, forKey: CodingKey.ambient.rawValue) aCoder.encode(self.diffuse, forKey: CodingKey.diffuse.rawValue) aCoder.encode(self.specular, forKey: CodingKey.specular.rawValue) aCoder.encode(self.roughness, forKey: CodingKey.roughness.rawValue) } } // MARK: - Finish constants and utilities extension Finish { /// No finish. static var none: Finish { return Finish(ambient: 0, diffuse: 0, specular: 0, roughness: 0) } /// Returns a random finish, ensuring that at least some light is reflected. static func random() -> Finish { let finishRange = 0...1 let ambient = finishRange.random(decimalPlaces: 2, above: 0.01) let diffuse = finishRange.random(decimalPlaces: 2, above: 0.01) let specular = finishRange.random(decimalPlaces: 2, above: 0.01) let roughness = finishRange.random(decimalPlaces: 2, above: 0.01) return Finish(ambient: ambient, diffuse: diffuse, specular: specular, roughness: roughness) } } extension Finish { static func == (lhs: Finish, rhs: Finish) -> Bool { return lhs.ambient == rhs.ambient && lhs.diffuse == rhs.diffuse && lhs.specular == rhs.specular && lhs.roughness == rhs.roughness } } extension Finish { override var description: String { return "Finish(ambient: \(self.ambient), diffuse: \(self.diffuse), specular: \(self.specular), roughness: \(self.roughness)))" } }
mit
c5dca3889b6bc6f28bbb7fd70e848df2
33.05
134
0.674009
4.410622
false
false
false
false
practicalswift/swift
test/PCMacro/func_decls.swift
7
1875
// RUN: %empty-directory(%t) // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -pc-macro -o %t/main %S/Inputs/PCMacroRuntime.swift %t/main.swift // RUN: %target-codesign %t/main // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/main2 %S/Inputs/PCMacroRuntime.swift %t/main.swift %S/Inputs/SilentPlaygroundsRuntime.swift // RUN: %target-codesign %t/main2 // RUN: %target-run %t/main2 | %FileCheck %s // REQUIRES: executable_test // FIXME: rdar://problem/30234450 PCMacro tests fail on linux in optimized mode // UNSUPPORTED: OS=linux-gnu // Lets check that the source ranges are correct on all different kinds of func // decls. #sourceLocation(file: "main.swift", line: 8) func function1(_ x: Int) -> Bool { return x == 1 } _ = function1(0) // CHECK: [12:1-12:17] pc before // CHECK-NEXT: [8:1-8:33] pc before // CHECK-NEXT: [8:1-8:33] pc after // CHECK-NEXT: [9:3-9:16] pc before // CHECK-NEXT: [9:3-9:16] pc after // CHECK-NEXT: [12:1-12:17] pc after func function2(_ x: Int) { } _ = function2(0) // CHECK-NEXT: [24:1-24:17] pc before // CHECK-NEXT: [21:1-21:25] pc before // CHECK-NEXT: [21:1-21:25] pc after // CHECK-NEXT: [24:1-24:17] pc after func function3(_ x: Int) throws { } _ = try! function3(0) // this test is XFAIL-ed in func_throw_notype and should be updated to 31:32 instead of 31:25 once fixed. // CHECK-NEXT: [34:1-34:22] pc before // CHECK-NEXT: [31:1-31:25] pc before // CHECK-NEXT: [31:1-31:25] pc after // CHECK-NEXT: [34:1-34:22] pc after func function4(_ x: Int) throws -> Bool { return x == 1 } _ = try! function4(0) // CHECK-NEXT: [44:1-44:22] pc before // CHECK-NEXT: [41:1-41:40] pc before // CHECK-NEXT: [41:1-41:40] pc after // CHECK-NEXT: [42:3-42:16] pc before // CHECK-NEXT: [42:3-42:16] pc after // CHECK-NEXT: [44:1-44:22] pc after
apache-2.0
bbdd2004528bcea407d98fcc7196bb6a
30.25
169
0.659733
2.615063
false
false
false
false
460467069/smzdm
什么值得买7.1.1版本/什么值得买(5月12日)/ZZSwiftCommon.swift
1
1747
// // ZZSwiftCommon.swift // 什么值得买 // // Created by Wang_ruzhou on 16/10/8. // Copyright © 2016年 Wang_ruzhou. All rights reserved. // import Foundation import YYText let kScreenBounds = UIScreen.main.bounds let kScreenWidth = YYScreenSize().width let kScreenHeight = YYScreenSize().height let kScreenScale = YYScreenScale() let kGlobalGrayColor = UIColor.init(hexString: "#666666") let kGlobalRedColor = UIColor.init(hexString: "#F04848") let kGlobalBlueColor = UIColor.init(hexString: "#1F2F6C") let kGlobalLightGrayColor = UIColor.init(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0) let kLineSpacing: CGFloat = 5 let kZDMPadding: CGFloat = 10 @objc protocol ZZActionDelegate: NSObjectProtocol{ @objc func itemDidClick(redirectData: ZZRedirectData) } extension String { static func zz_string(floatValue: Float) -> String? { let number = NSNumber.init(value: floatValue) let formatter = NumberFormatter() formatter.numberStyle = .percent return formatter.string(from: number) } } func screenAdaptation(fromPixelValue: CGFloat) -> CGFloat { return kScreenWidth / 750.0 * fromPixelValue } extension NSAttributedString { static func commonAttributedText(title: String) -> NSAttributedString { let text = NSMutableAttributedString.init(string: title) text.yy_lineSpacing = 10 text.yy_lineBreakMode = .byTruncatingTail text.yy_font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium) return text } } func bindingErrorToInterface(_ error: Swift.Error) { let error = "Binding error to UI: \(error)" #if DEBUG fatalError() #else print(error) #endif }
mit
bb9f584edef6448c9d82ca21e16c4ba3
28.389831
109
0.700692
3.853333
false
false
false
false
OnMap/Localization
OML10nTests/Core/UITextView+LocalizableTests.swift
1
2845
// // UITextView+LocalizableTests.swift // OML10nTests // // Created by Alex Alexandrovych on 03/02/2018. // Copyright © 2018 OnMap. All rights reserved. // import XCTest class UITextViewLocalizableTests: XCTestCase { // MARK: Constants (from Localizable.strings) let key = "Test.TextView" let unknownKey = "Test.Unknown" enum Strings { static let text = "test text view text" } // MARK: Properties var textView: UITextView! // MARK: Setup override func setUp() { super.setUp() textView = UITextView() textView.bundle = Bundle(for: type(of: self)) } // MARK: Tests func testTextKey() { textView.localizationKey = key XCTAssertEqual(textView.text, Strings.text) } func testAttributedTextKey() { let colorKey: NSAttributedStringKey = .foregroundColor let colorAttribute: UIColor = .red let fontKey: NSAttributedStringKey = .font let fontAttribute: UIFont = UIFont.systemFont(ofSize: 20) let attributes = [colorKey: colorAttribute, fontKey: fontAttribute] textView.attributedText = NSAttributedString(string: "Test", attributes: attributes) textView.localizationKey = key XCTAssertEqual(textView.text, Strings.text) let newAttributes = textView.attributedText?.attributes(at: 0, effectiveRange: nil) if let newAttributes = newAttributes, let color = newAttributes[colorKey] as? UIColor, let font = newAttributes[fontKey] as? UIFont { XCTAssertEqual(newAttributes.count, attributes.count) XCTAssertEqual(color, colorAttribute) XCTAssertEqual(font, fontAttribute) } else { XCTFail("Assert attributes failure") } } func testWrongKey() { textView.localizationKey = unknownKey XCTAssertEqual(textView.text, "") } func testWrongKeyLeavesPreviousValues() { textView.localizationKey = key textView.localizationKey = unknownKey XCTAssertEqual(textView.text, Strings.text) } func testEmptyKey() { textView.localizationKey = "" XCTAssertEqual(textView.text, "") } func testEmptyKeyLeavesPreviousValues() { textView.localizationKey = key textView.localizationKey = "" XCTAssertEqual(textView.text, Strings.text) } func testNilKey() { textView.localizationKey = nil XCTAssertEqual(textView.text, "") } func testNilKeyLeavesPreviousValues() { textView.localizationKey = key textView.localizationKey = nil XCTAssertEqual(textView.text, Strings.text) } func testLocalizationKeySets() { textView.localizationKey = key XCTAssertEqual(textView.localizationKey, key) } }
mit
6043957eb81ed85a7ba258a94172329f
26.346154
92
0.651547
4.828523
false
true
false
false
fitpay/fitpay-ios-sdk
FitpaySDK/A2AVerification/A2AVerificationError.swift
1
793
/// Errors for A2AVerificationRequest public enum A2AVerificationError: String { /// Created by the SDK if A2AVerificationRequest can't be parsed correctly case cantProcess = "cantProcessVerification" /// Sent by the bank in case of declined case declined = "appToAppDeclined" /// Sent by the bank in case of failure case failure = "appToAppFailure" /// Used for non-supported card types - currently Mastercard on iOS case notSupported = "appToAppNotSupported" /// Can be used by OEM app to let the webview know there was an answer, a pop-up will be shown case unknown = "unknown" /// Can be used by OEM app to let the webview know there was an answer, no pop-up will display case silentUnknown = "silentUnknown" }
mit
0e66eddb19a126a16be1492fc033f353
36.761905
98
0.69483
4.430168
false
false
false
false
vhart/PPL-iOS
PPL-iOS/PPL-iOS/WeightChangeViewController.swift
1
2555
// // WeightChangeViewController.swift // PPL-iOS // // Created by Jovanny Espinal on 2/24/16. // Copyright © 2016 Jovanny Espinal. All rights reserved. // import UIKit protocol WeightChangeViewControllerDelegate { func weightChanged(exerciseIndex: Int, weight: Double) } class WeightChangeViewController: UIViewController { @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var weightLabel: UILabel! var exerciseIndex: Int! var exerciseName: String! var weight: Double! var barbellExercises = [ExerciseName.deadlift, ExerciseName.barbellRow, ExerciseName.benchPress, ExerciseName.overheadPress, ExerciseName.squat, ExerciseName.romanianDeadlift, ExerciseName.legPress] var progressionScheme: ProgressionScheme! var delegate: WeightChangeViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] navigationBar.tintColor = UIColor.whiteColor() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) updateLabel() } @IBAction func decreaseWeight(sender: AnyObject) { if progressionScheme == .Accessory { weight = weight - 2.5 } else { weight = weight - 5.0 } updateLabel() } @IBAction func increaseWeight(sender: AnyObject) { if progressionScheme == .Accessory { weight = weight + 2.5 } else { weight = weight + 5.0 } updateLabel() } func updateLabel() { weightLabel.text = "\(weight)" if barbellExercises.contains(exerciseName) { if weight <= 45.0 { navigationBar.topItem!.title = "Lift The Empty Bar" } else { navigationBar.topItem!.title = "Add \((weight-45.0)/2)lbs/side" } } else { navigationBar.topItem!.title = "Change Exercise Weight" } } @IBAction func saveButtonTapped(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) self.delegate?.weightChanged(exerciseIndex, weight: weight) } @IBAction func cancelButtonTapped(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
2e22fc28319ea6effc32bcaeea872403
27.696629
202
0.624511
4.883365
false
false
false
false
fiveagency/ios-five-ui-components
FiveUIComponents/Classes/Animators/DelayedCellAnimation.swift
1
2016
// // DelayedCellAnimation.swift // FiveUIComponents // // Created by Denis Mendica on 2/17/17. // Copyright © 2017 Five Agency. All rights reserved. // import Foundation /** Predefined animations for DelayedCellLoadingAnimator. */ public enum DelayedCellAnimation { /** Slide from bottom and fade in. */ case slide /** Slightly rotate and fade in. */ case rotate /** Scale up and fade in. */ case pop /** Block that sets up the cell before it is animated. */ var setupInitialState: SetupDelayedCellClosure { switch self { case .slide: return { cell, layoutAttributes in cell.alpha = 0 let verticalOffset = 0.3 * layoutAttributes.frame.height cell.transform = layoutAttributes.transform.translatedBy(x: 0, y: verticalOffset) } case .rotate: return { cell, layoutAttributes in cell.alpha = 0 cell.transform = layoutAttributes.transform.rotated(by: CGFloat(-M_PI / 10)) } case .pop: return { cell, layoutAttributes in cell.alpha = 0 cell.transform = layoutAttributes.transform.scaledBy(x: 0.7, y: 0.7) } } } /** Block that defines the cell state after animation. */ var setupFinalState: SetupDelayedCellClosure { switch self { case .slide: return { cell, layoutAttributes in cell.alpha = 1 cell.transform = layoutAttributes.transform } case .rotate: return { cell, layoutAttributes in cell.alpha = 1 cell.transform = layoutAttributes.transform } case .pop: return { cell, layoutAttributes in cell.alpha = 1 cell.transform = layoutAttributes.transform } } } }
mit
d6a28833f21c50c974da4e1ebd001e6c
25.513158
97
0.544417
4.987624
false
false
false
false
victorlin/ReactiveCocoa
ReactiveCocoa/Swift/Event.swift
1
3784
// // Event.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2015-01-16. // Copyright (c) 2015 GitHub. All rights reserved. // /// Represents a signal event. /// /// Signals must conform to the grammar: /// `Next* (Failed | Completed | Interrupted)?` public enum Event<Value, Error: Swift.Error> { /// A value provided by the signal. case next(Value) /// The signal terminated because of an error. No further events will be /// received. case failed(Error) /// The signal successfully terminated. No further events will be received. case completed /// Event production on the signal has been interrupted. No further events /// will be received. /// /// - important: This event does not signify the successful or failed /// completion of the signal. case interrupted /// Whether this event indicates signal termination (i.e., that no further /// events will be received). public var isTerminating: Bool { switch self { case .next: return false case .failed, .completed, .interrupted: return true } } /// Lift the given closure over the event's value. /// /// - important: The closure is called only on `next` type events. /// /// - parameters: /// - f: A closure that accepts a value and returns a new value /// /// - returns: An event with function applied to a value in case `self` is a /// `next` type of event. public func map<U>(_ f: (Value) -> U) -> Event<U, Error> { switch self { case let .next(value): return .next(f(value)) case let .failed(error): return .failed(error) case .completed: return .completed case .interrupted: return .interrupted } } /// Lift the given closure over the event's error. /// /// - important: The closure is called only on failed type event. /// /// - parameters: /// - f: A closure that accepts an error object and returns /// a new error object /// /// - returns: An event with function applied to an error object in case /// `self` is a `.Failed` type of event. public func mapError<F>(_ f: (Error) -> F) -> Event<Value, F> { switch self { case let .next(value): return .next(value) case let .failed(error): return .failed(f(error)) case .completed: return .completed case .interrupted: return .interrupted } } /// Unwrap the contained `next` value. public var value: Value? { if case let .next(value) = self { return value } else { return nil } } /// Unwrap the contained `Error` value. public var error: Error? { if case let .failed(error) = self { return error } else { return nil } } } public func == <Value: Equatable, Error: Equatable> (lhs: Event<Value, Error>, rhs: Event<Value, Error>) -> Bool { switch (lhs, rhs) { case let (.next(left), .next(right)): return left == right case let (.failed(left), .failed(right)): return left == right case (.completed, .completed): return true case (.interrupted, .interrupted): return true default: return false } } extension Event: CustomStringConvertible { public var description: String { switch self { case let .next(value): return "NEXT \(value)" case let .failed(error): return "FAILED \(error)" case .completed: return "COMPLETED" case .interrupted: return "INTERRUPTED" } } } /// Event protocol for constraining signal extensions public protocol EventProtocol { /// The value type of an event. associatedtype Value /// The error type of an event. If errors aren't possible then `NoError` can /// be used. associatedtype Error: Swift.Error /// Extracts the event from the receiver. var event: Event<Value, Error> { get } } extension Event: EventProtocol { public var event: Event<Value, Error> { return self } }
mit
97238953bc2933de59e656fdbf25f455
21.933333
114
0.65777
3.436876
false
false
false
false
the-grid/Portal
PortalTests/Fixtures/PublisherFixtures.swift
1
1443
import Argo import Foundation import Portal private let domain = "gridbear.com" private let favicon = "https://gridbear.com" private let name = "Grid Bear" private let url = "https://gridbear.com/favicon.png" let publisherResponseBody: [String: AnyObject] = [ "domain": domain, "favicon": favicon, "name": name, "url": url ] let publisherJson: JSON = .Object([ "domain": .String(domain), "favicon": .String(favicon), "name": .String(name), "url": .String(url) ]) let publisherModel = Publisher( domain: domain, favicon: NSURL(string: favicon)!, name: name, url: NSURL(string: url)! ) private let updatedDomain = "gridbeard.com" private let updatedFavicon = "https://gridbeard.com" private let updatedName = "Grid Beard" private let updatedUrl = "https://gridbeard.com/favicon.png" let updatedPublisherResponseBody: [String: AnyObject] = [ "domain": updatedDomain, "favicon": updatedFavicon, "name": updatedName, "url": updatedUrl ] let updatedPublisherJson: JSON = .Object([ "domain": .String(updatedDomain), "favicon": .String(updatedFavicon), "name": .String(updatedName), "url": .String(updatedUrl) ]) let updatedPublisherModel: Publisher = { var model = publisherModel model.domain = updatedDomain model.favicon = NSURL(string: updatedFavicon)! model.name = updatedName model.url = NSURL(string: updatedUrl)! return model }()
mit
32566a2199981a23f084d44ea5e90114
23.87931
60
0.681913
3.6075
false
false
false
false
3DprintFIT/octoprint-ios-client
OctoPhone/AppDelegate.swift
1
2797
// // AppDelegate.swift // OctoPhone // // Created by Josef Dolezal on 25/10/16. // Copyright © 2016 Josef Dolezal. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { /// Base app window var window: UIWindow? /// Initial flow coordinator var coordinator: CoordinatorType? func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { let window = UIWindow(frame: UIScreen.main.bounds) let navigationController = UINavigationController() let coordinator = AppCoordinator(navigationController: navigationController) window.backgroundColor = UIColor.white window.rootViewController = navigationController coordinator.start() window.makeKeyAndVisible() self.window = window self.coordinator = coordinator return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur // for certain types of temporary interruptions (such as an incoming phone call or // SMS message) or when the user quits the application and it begins the transition to // the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering // callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store // enough application state information to restore your application to its current state in // case it is terminated later. // If your application supports background execution, this method is called instead of // applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can // undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was // inactive. If the application was previously in the background, optionally refresh // the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. // See also applicationDidEnterBackground:. } }
mit
80b9bb567191917683d05c00592b54c7
37.30137
100
0.702074
5.6714
false
false
false
false
totocaster/Typist
Typist-Demo/ViewController.swift
1
3081
// // ViewController.swift // Typist // // Created by Toto Tvalavadze on 2016/09/26. // Copyright © 2016 Toto Tvalavadze. All rights reserved. // import UIKit class ViewController: UIViewController { let keyboard = Typist.shared @IBOutlet weak var tableView: UITableView! { didSet { tableView.tableHeaderView = UIView() tableView.tableFooterView = UIView() } } @IBOutlet weak var toolbar: UIToolbar! @IBOutlet weak var textField: UITextField! @IBOutlet weak var bottom: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // keyboard input accessory view support textField.inputAccessoryView = UIView(frame: toolbar.bounds) // keyboard frame observer keyboard .toolbar(scrollView: tableView) .on(event: .willChangeFrame) { [unowned self] options in let height = options.endFrame.height UIView.animate(withDuration: 0) { self.bottom.constant = max(0, height - self.toolbar.bounds.height) self.tableView.contentInset.bottom = max(self.toolbar.bounds.height, height) self.tableView.scrollIndicatorInsets.bottom = max(self.toolbar.bounds.height, height) self.toolbar.layoutIfNeeded() } self.navigationItem.prompt = options.endFrame.debugDescription } .on(event: .willHide) { [unowned self] options in // .willHide is used in cases when keyboard is *not* dismiss interactively. // e.g. when `.resignFirstResponder()` is called on textField. UIView.animate(withDuration: options.animationDuration, delay: 0, options: UIView.AnimationOptions(curve: options.animationCurve), animations: { self.bottom.constant = 0 self.tableView.contentInset.bottom = self.toolbar.bounds.height self.tableView.scrollIndicatorInsets.bottom = self.toolbar.bounds.height self.toolbar.layoutIfNeeded() }, completion: nil) } .start() self.navigationItem.prompt = "Keybaord frame will appear here." self.title = "Typist Demo" } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style: .default, reuseIdentifier: "Cell") cell.textLabel?.text = "Cell \(indexPath.row)" return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) self.textField.resignFirstResponder() } }
mit
ee8ecfbb37f853abd2dbbeb2614bd1e8
37.5
160
0.625
5.150502
false
false
false
false
yemeksepeti/YSSegmentedControl
YSSegmentedControl/YSSegmentedControl/YSSegmentedControl.swift
1
15292
// // YSSegmentedControl.swift // yemeksepeti // // Created by Cem Olcay on 22/04/15. // Copyright (c) 2015 yemeksepeti. All rights reserved. // import UIKit // MARK: - Appearance public struct YSSegmentedControlAppearance { public var backgroundColor: UIColor public var selectedBackgroundColor: UIColor public var unselectedTextAttributes: [String : Any] public var selectedTextAttributes: [String : Any] public var bottomLineColor: UIColor public var selectorColor: UIColor public var bottomLineHeight: CGFloat public var selectorHeight: CGFloat public var itemTopPadding: CGFloat /** The distance between the top of the selector and the bottom of the label. If this is nil, then the selector will be anchored on the bottom of the segmented control; otherwise the selector will be this distance from the bottom of the label. */ public var selectorOffsetFromLabel: CGFloat? /** Whether or not the selector spans the full width of the YSSegmentedControlItem. If set to true, the selector will span the entire width of the item; if set to false, the selector will span the entire width of the label. */ public var selectorSpansFullItemWidth: Bool /** Whether or not the labels on the ends (first and last) float to the edges or are centered within the item. If set to `true`, then the labels float to the edges; if set to `false`, then the labels are centered. Default value is `false`. */ public var labelsOnEndsFloatToEdges: Bool } // MARK: - Control Item typealias YSSegmentedControlItemAction = (_ item: YSSegmentedControlItem) -> Void class YSSegmentedControlItem: UIControl { // MARK: Properties private var willPress: YSSegmentedControlItemAction? private var didPress: YSSegmentedControlItemAction? var label: UILabel! let labelAlignment: NSTextAlignment // MARK: Init init(frame: CGRect, text: String, appearance: YSSegmentedControlAppearance, willPress: YSSegmentedControlItemAction?, didPress: YSSegmentedControlItemAction?, labelAlignment: NSTextAlignment) { self.willPress = willPress self.didPress = didPress self.labelAlignment = labelAlignment super.init(frame: frame) commonInit() label.attributedText = NSAttributedString(string: text, attributes: appearance.unselectedTextAttributes) } required init?(coder aDecoder: NSCoder) { self.labelAlignment = .center super.init (coder: aDecoder) commonInit() } private func commonInit() { label = UILabel() label.textAlignment = .center label.translatesAutoresizingMaskIntoConstraints = false addSubview(label) let attribute: NSLayoutAttribute switch labelAlignment { case .left: attribute = .leading case .right: attribute = .trailing default: attribute = .centerX } addConstraint(NSLayoutConstraint(item: label, attribute: attribute, relatedBy: .equal, toItem: self, attribute: attribute, multiplier: 1.0, constant: 0.0)) addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0)) let views: [String: Any] = ["label": label] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=0)-[label]-(>=0)-|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=0)-[label]-(>=0)-|", options: [], metrics: nil, views: views)) } // MARK: UI Helpers func updateLabelAttributes(_ attributes: [String : Any]) { guard let labelText = label.text else { return } label.attributedText = NSAttributedString(string: labelText, attributes: attributes) } // MARK: Events override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { willPress?(self) } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { didPress?(self) } } // MARK: - Control public protocol YSSegmentedControlDelegate: class { func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) func segmentedControl(_ segmentedControl: YSSegmentedControl, didPressItemAt index: Int) } public typealias YSSegmentedControlAction = (_ segmentedControl: YSSegmentedControl, _ index: Int) -> Void public class YSSegmentedControl: UIView { // MARK: Properties weak var delegate: YSSegmentedControlDelegate? public var action: YSSegmentedControlAction? private var selectedIndex = 0 public var appearance: YSSegmentedControlAppearance! { didSet { self.draw() } } public var titles: [String]! { didSet { if appearance == nil { defaultAppearance() } else { self.draw() } } } var items = [YSSegmentedControlItem]() var selector = UIView() var bottomLine = CALayer() fileprivate var selectorLeadingConstraint: NSLayoutConstraint? fileprivate var selectorWidthConstraint: NSLayoutConstraint? fileprivate var selectorBottomConstraint: NSLayoutConstraint? // MARK: Init public init (frame: CGRect, titles: [String], action: YSSegmentedControlAction? = nil) { super.init (frame: frame) self.action = action self.titles = titles defaultAppearance() } required public init? (coder aDecoder: NSCoder) { super.init (coder: aDecoder) } // MARK: Draw private func reset() { for sub in subviews { let v = sub v.removeFromSuperview() } items.removeAll() } private func draw() { reset() backgroundColor = appearance.backgroundColor for (index, title) in titles.enumerated() { let labelAlignment: NSTextAlignment if appearance.labelsOnEndsFloatToEdges { switch index { case 0: labelAlignment = .left case titles.count - 1: labelAlignment = .right default: labelAlignment = .center } } else { labelAlignment = .center } let item = YSSegmentedControlItem( frame: .zero, text: title, appearance: appearance, willPress: { [weak self] segmentedControlItem in guard let weakSelf = self else { return } let index = weakSelf.items.index(of: segmentedControlItem)! weakSelf.delegate?.segmentedControl(weakSelf, willPressItemAt: index) }, didPress: { [weak self] segmentedControlItem in guard let weakSelf = self else { return } let index = weakSelf.items.index(of: segmentedControlItem)! weakSelf.selectItem(at: index, withAnimation: true) weakSelf.action?(weakSelf, index) weakSelf.delegate?.segmentedControl(weakSelf, didPressItemAt: index) }, labelAlignment: labelAlignment) addSubview(item) items.append(item) } // bottom line bottomLine.backgroundColor = appearance.bottomLineColor.cgColor layer.addSublayer(bottomLine) // selector selector.translatesAutoresizingMaskIntoConstraints = false selector.backgroundColor = appearance.selectorColor addSubview(selector) addConstraint(NSLayoutConstraint(item: selector, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: appearance.selectorHeight)) selectItem(at: selectedIndex, withAnimation: true) setNeedsLayout() } public override func layoutSubviews() { super.layoutSubviews() let width = frame.size.width / CGFloat(titles.count) var currentX: CGFloat = 0 for item in items { item.frame = CGRect( x: currentX, y: appearance.itemTopPadding, width: width, height: frame.size.height - appearance.itemTopPadding) currentX += width } bottomLine.frame = CGRect( x: 0, y: frame.size.height - appearance.bottomLineHeight, width: frame.size.width, height: appearance.bottomLineHeight) } private func defaultAppearance() { appearance = YSSegmentedControlAppearance( backgroundColor: .clear, selectedBackgroundColor: .clear, unselectedTextAttributes: [:], selectedTextAttributes: [:], bottomLineColor: .black, selectorColor: .black, bottomLineHeight: 0.5, selectorHeight: 2, itemTopPadding: 0, selectorOffsetFromLabel: nil, selectorSpansFullItemWidth: true, labelsOnEndsFloatToEdges: false) } // MARK: Select public func selectItem(at index: Int, withAnimation animation: Bool) { self.selectedIndex = index moveSelector(at: index, withAnimation: animation) for item in items { if item == items[index] { item.updateLabelAttributes(appearance.selectedTextAttributes) item.backgroundColor = appearance.selectedBackgroundColor } else { item.updateLabelAttributes(appearance.unselectedTextAttributes) item.backgroundColor = appearance.backgroundColor } } } private func moveSelector(at index: Int, withAnimation animation: Bool) { guard items.count > selectedIndex else { return } layoutIfNeeded() if let selectorWidthConstraint = selectorWidthConstraint { removeConstraint(selectorWidthConstraint) } if let selectorLeadingConstraint = selectorLeadingConstraint { removeConstraint(selectorLeadingConstraint) } if let selectorBottomConstraint = selectorBottomConstraint { removeConstraint(selectorBottomConstraint) } let item = items[selectedIndex] let horizontalConstrainingView: UIView if appearance.selectorSpansFullItemWidth { horizontalConstrainingView = item } else { horizontalConstrainingView = item.label } selectorLeadingConstraint = NSLayoutConstraint(item: selector, attribute: .leading, relatedBy: .equal, toItem: horizontalConstrainingView, attribute: .leading, multiplier: 1.0, constant: 0) selectorWidthConstraint = NSLayoutConstraint(item: selector, attribute: .width, relatedBy: .equal, toItem: horizontalConstrainingView, attribute: .width, multiplier: 1.0, constant: 0) if let selectorOffsetFromLabel = appearance.selectorOffsetFromLabel { selectorBottomConstraint = NSLayoutConstraint(item: selector, attribute: .top, relatedBy: .equal, toItem: item.label, attribute: .bottom, multiplier: 1.0, constant: selectorOffsetFromLabel) } else { selectorBottomConstraint = NSLayoutConstraint(item: selector, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0) } addConstraints([selectorWidthConstraint!, selectorLeadingConstraint!, selectorBottomConstraint!]) UIView.animate(withDuration: animation ? 0.3 : 0, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { [unowned self] in self.layoutIfNeeded() }, completion: nil) } }
mit
b93b38ab1f1c8b441056c00a54ddbeb1
34.645688
112
0.504708
6.634273
false
false
false
false
chrisjmendez/swift-exercises
Walkthroughs/MyPresentation/Carthage/Checkouts/Cartography/CartographyTests/EdgeSpec.swift
15
10735
import Cartography import Nimble import Quick class EdgeSpec: QuickSpec { override func spec() { var window: TestWindow! var view: TestView! beforeEach { window = TestWindow(frame: CGRectMake(0, 0, 400, 400)) view = TestView(frame: CGRectZero) window.addSubview(view) constrain(view) { view in view.height == 200 view.width == 200 } } describe("LayoutProxy.top") { it("should support relative equalities") { constrain(view) { view in view.top == view.superview!.top } window.layoutIfNeeded() expect(view.frame.minY).to(equal(0)) } it("should support relative inequalities") { constrain(view) { view in view.top <= view.superview!.top view.top >= view.superview!.top } window.layoutIfNeeded() expect(view.frame.minY).to(equal(0)) } it("should support addition") { constrain(view) { view in view.top == view.superview!.top + 100 } window.layoutIfNeeded() expect(view.frame.minY).to(equal(100)) } it("should support subtraction") { constrain(view) { view in view.top == view.superview!.top - 100 } window.layoutIfNeeded() expect(view.frame.minY).to(equal(-100)) } } describe("LayoutProxy.right") { it("should support relative equalities") { constrain(view) { view in view.right == view.superview!.right } window.layoutIfNeeded() expect(view.frame.maxX).to(equal(400)) } it("should support relative inequalities") { constrain(view) { view in view.right <= view.superview!.right view.right >= view.superview!.right } window.layoutIfNeeded() expect(view.frame.maxX).to(equal(400)) } it("should support addition") { constrain(view) { view in view.right == view.superview!.right + 100 } window.layoutIfNeeded() expect(view.frame.maxX).to(equal(500)) } it("should support subtraction") { constrain(view) { view in view.right == view.superview!.right - 100 } window.layoutIfNeeded() expect(view.frame.maxX).to(equal(300)) } } describe("LayoutProxy.bottom") { it("should support relative equalities") { constrain(view) { view in view.bottom == view.superview!.bottom } window.layoutIfNeeded() expect(view.frame.maxY).to(equal(400)) } it("should support relative inequalities") { constrain(view) { view in view.bottom <= view.superview!.bottom view.bottom >= view.superview!.bottom } window.layoutIfNeeded() expect(view.frame.maxY).to(equal(400)) } it("should support addition") { constrain(view) { view in view.bottom == view.superview!.bottom + 100 } window.layoutIfNeeded() expect(view.frame.maxY).to(equal(500)) } it("should support subtraction") { constrain(view) { view in view.bottom == view.superview!.bottom - 100 } window.layoutIfNeeded() expect(view.frame.maxY).to(equal(300)) } } describe("LayoutProxy.left") { it("should support relative equalities") { constrain(view) { view in view.left == view.superview!.left } window.layoutIfNeeded() expect(view.frame.minX).to(equal(0)) } it("should support relative inequalities") { constrain(view) { view in view.left <= view.superview!.left view.left >= view.superview!.left } window.layoutIfNeeded() expect(view.frame.minX).to(equal(0)) } it("should support addition") { constrain(view) { view in view.left == view.superview!.left + 100 } window.layoutIfNeeded() expect(view.frame.minX).to(equal(100)) } it("should support subtraction") { constrain(view) { view in view.left == view.superview!.left - 100 } window.layoutIfNeeded() expect(view.frame.minX).to(equal(-100)) } } describe("LayoutProxy.centerX") { it("should support relative equalities") { constrain(view) { view in view.centerX == view.superview!.centerX } window.layoutIfNeeded() expect(view.frame.midX).to(equal(200)) } it("should support relative inequalities") { constrain(view) { view in view.centerX <= view.superview!.centerX view.centerX >= view.superview!.centerX } window.layoutIfNeeded() expect(view.frame.midX).to(equal(200)) } it("should support addition") { constrain(view) { view in view.centerX == view.superview!.centerX + 100 } window.layoutIfNeeded() expect(view.frame.midX).to(equal(300)) } it("should support subtraction") { constrain(view) { view in view.centerX == view.superview!.centerX - 100 } window.layoutIfNeeded() expect(view.frame.midX).to(equal(100)) } it("should support multiplication") { constrain(view) { view in view.centerX == view.superview!.centerX * 2 } window.layoutIfNeeded() expect(view.frame.midX).to(equal(400)) } it("should support division") { constrain(view) { view in view.centerX == view.superview!.centerX / 2 } window.layoutIfNeeded() expect(view.frame.midX).to(equal(100)) } } describe("LayoutProxy.centerY") { it("should support relative equalities") { constrain(view) { view in view.centerY == view.superview!.centerY } window.layoutIfNeeded() expect(view.frame.midY).to(equal(200)) } it("should support relative inequalities") { constrain(view) { view in view.centerY <= view.superview!.centerY view.centerY >= view.superview!.centerY } window.layoutIfNeeded() expect(view.frame.midY).to(equal(200)) } it("should support addition") { constrain(view) { view in view.centerY == view.superview!.centerY + 100 } window.layoutIfNeeded() expect(view.frame.midY).to(equal(300)) } it("should support subtraction") { constrain(view) { view in view.centerY == view.superview!.centerY - 100 } window.layoutIfNeeded() expect(view.frame.midY).to(equal(100)) } it("should support multiplication") { constrain(view) { view in view.centerY == view.superview!.centerY * 2 } window.layoutIfNeeded() expect(view.frame.midY).to(equal(400)) } it("should support division") { constrain(view) { view in view.centerY == view.superview!.centerY / 2 } window.layoutIfNeeded() expect(view.frame.midY).to(equal(100)) } } #if os(iOS) describe("on iOS only") { beforeEach { window.layoutMargins = UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 40) } describe("LayoutProxy.topMargin") { it("should support relative equalities") { constrain(view) { view in view.top == view.superview!.topMargin } window.layoutIfNeeded() expect(view.frame.minY).to(equal(10)) } } describe("LayoutProxy.rightMargin") { it("should support relative equalities") { constrain(view) { view in view.right == view.superview!.rightMargin } window.layoutIfNeeded() expect(view.frame.maxX).to(equal(360)) } } describe("LayoutProxy.bottomMargin") { it("should support relative equalities") { constrain(view) { view in view.bottom == view.superview!.bottomMargin } window.layoutIfNeeded() expect(view.frame.maxY).to(equal(370)) } } describe("LayoutProxy.leftMargin") { it("should support relative equalities") { constrain(view) { view in view.left == view.superview!.leftMargin } window.layoutIfNeeded() expect(view.frame.minX).to(equal(20)) } } } #endif } }
mit
6d8435a54b0593d1183b841b6418ee9d
27.474801
93
0.450675
5.479837
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/BasicChartTypes/DigitalMountainChartView.swift
1
2533
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // DigitalMountainChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class DigitalMountainChartView: SingleChartLayout { override func initExample() { let xAxis = SCIDateTimeAxis() xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) let yAxis = SCINumericAxis() yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1)) let priceData = DataManager.getPriceDataIndu() let dataSeries = SCIXyDataSeries(xType: .dateTime, yType: .double) dataSeries.appendRangeX(SCIGeneric(priceData!.dateData()), y: SCIGeneric(priceData!.closeData()), count: priceData!.size()) let rSeries = SCIFastMountainRenderableSeries() rSeries.dataSeries = dataSeries rSeries.zeroLineY = 10000 rSeries.isDigitalLine = true rSeries.areaStyle = SCILinearGradientBrushStyle(colorCodeStart: 0xAAFF8D42, finish: 0x88090E11, direction: .vertical) rSeries.strokeStyle = SCISolidPenStyle(colorCode: 0xAAFFC9A8, withThickness: 1.0) let xAxisDragmodifier = SCIXAxisDragModifier() xAxisDragmodifier.clipModeX = .none let yAxisDragmodifier = SCIYAxisDragModifier() yAxisDragmodifier.dragMode = .pan SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) self.surface.renderableSeries.add(rSeries) self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [xAxisDragmodifier, yAxisDragmodifier, SCIPinchZoomModifier(), SCIZoomExtentsModifier(), SCITooltipModifier()]) rSeries.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) } } }
mit
dfb2ed0069777f577a3ead82df68e1a8
47.653846
196
0.656522
4.6337
false
false
false
false
nekrich/GlobalMessageService-iOS
Source/Core/Message/GMSMessageFetcher.swift
1
14394
// // GMSMessageFetcher.swift // Pods // // Created by Vitalii Budnik on 1/25/16. // // import Foundation import CoreData /** `Class` fetches delivered messages from Global Message Services servers */ public final class GlobalMessageServiceMessagesFetcher { /// Private initializer private init() { } /** Fetches messages from Global Message Services servers - Parameter date: `NSDate` concrete date for which you need to get messages - Parameter fetch: `Bool` indicates to fetch message from remote server if no stored data available. `true` - fetch data if there is no cached data, `false` otherwise. Default value is `true` - Parameter completionHandler: The code to be executed once the request has finished. (optional). This block takes no parameters. Returns `Result` `<[GlobalMessageServiceMessage], GlobalMessageServiceError>`, where `result.value` is always contains `Array<GMSMessage>` if there no error occurred, otherwise see `result.error` */ public class func fetchMessages( forDate date: NSDate, fetch: Bool = true, completionHandler: ((GlobalMessageServiceResult<[GlobalMessageServiceMessage]>) -> Void)? = .None) // swiftlint:disable:this line_length { let completion = completionHandlerInMainThread(completionHandler) if !GlobalMessageService.authorized { completion?(.Failure(.NotAuthorized)) } if date.timeIntervalSinceReferenceDate > NSDate().timeIntervalSinceReferenceDate { completion?(.Success([])) } let lastFetchedTimeInterval: NSTimeInterval // let completion: (Result<[GlobalMessageServiceMessage], GlobalMessageServiceError>) -> Void = { result in // if let completionHandler = completionHandler { // dispatch_async(dispatch_get_main_queue()) { // completionHandler(result) // } // } // } let gmsMessages: [GlobalMessageServiceMessage] if let fetchedDate = GMSInboxFetchedDate.getInboxFetchedDate( forDate: date.timeIntervalSinceReferenceDate) // swiftlint:disable:this opening_brace { let messages: [GMSInboxMessage] // swiftlint:disable empty_count if let fetchedMessages = fetchedDate.messages where fetchedMessages.count > 0 { // swiftlint:enable empty_count messages = (fetchedMessages.allObjects as? [GMSInboxMessage])?.filter { !$0.deletionMark } ?? [] } else { messages = [] } gmsMessages = messages .filter { !$0.deletionMark } .flatMap { GlobalMessageServiceMessage(message: $0) } if fetchedDate.lastMessageDate == date.endOfDay().timeIntervalSinceReferenceDate { completion?(.Success(gmsMessages)) return } lastFetchedTimeInterval = fetchedDate.lastMessageDate } else { gmsMessages = [] lastFetchedTimeInterval = date.startOfDay().timeIntervalSinceReferenceDate } if !fetch { completion?(.Success(gmsMessages)) return } fetchSMS(forDate: lastFetchedTimeInterval) { result in guard let sms: [GlobalMessageServiceMessage] = result.value(completionHandler) else { return } GlobalMessageServiceMessagesFetcher.fetchViber(forDate: lastFetchedTimeInterval) { result in guard let viber = result.value(completionHandler) else { return } GlobalMessageServiceMessagesFetcher.fetchPushNotifications( forDate: lastFetchedTimeInterval) { result in guard let push = result.value(completionHandler) else { return } completion?(.Success(gmsMessages + sms + viber + push)) } } } } /** Fetches `.Viber` messages from Global Message Services servers - Parameter date: `NSTimeInterval` concrete time interval *since 00:00:00 UTC on 1 January 2001* for which you need to get messages - Parameter completionHandler: The code to be executed once the request has finished. (optional). This block takes no parameters. Returns `Result` `<[GlobalMessageServiceMessage], GlobalMessageServiceError>`, where `result.value` is always contains `Array<GMSMessage>` if there no error occurred, otherwise see `result.error` */ private class func fetchViber( forDate date: NSTimeInterval, completionHandler completion: (GlobalMessageServiceResult<[GlobalMessageServiceMessage]>) -> Void) // swiftlint:disable:this line_length { fetch(.Viber, date: date, completionHandler: completion) } /** Fetches `.SMS` messages from Global Message Services servers - Parameter date: `NSTimeInterval` concrete time interval *since 00:00:00 UTC on 1 January 2001* for which you need to get messages - Parameter completionHandler: The code to be executed once the request has finished. (optional). This block takes no parameters. Returns `Result` `<[GlobalMessageServiceMessage], GlobalMessageServiceError>`, where `result.value` is always contains `Array<GMSMessage>` if there no error occurred, otherwise see `result.error` */ private class func fetchSMS( forDate date: NSTimeInterval, completionHandler completion: (GlobalMessageServiceResult<[GlobalMessageServiceMessage]>) -> Void) // swiftlint:disable:this line_length { fetch(.SMS, date: date, completionHandler: completion) } /** Gets recieved push-notification from `GMSInboxFetchedDate` - Parameter date: `NSTimeInterval` concrete time interval *since 00:00:00 UTC on 1 January 2001* for which you need to get messages - Parameter completionHandler: The code to be executed once the request has finished. (optional). This block takes no parameters. Returns `Result` `<[GlobalMessageServiceMessage], GlobalMessageServiceError>`, where `result.value` is always contains `Array<GMSMessage>` if there no error occurred, otherwise see `result.error` */ private class func fetchPushNotifications( forDate date: NSTimeInterval, completionHandler completion: (GlobalMessageServiceResult<[GlobalMessageServiceMessage]>) -> Void) // swiftlint:disable:this line_length { completion(.Success(getPushNotifications(forDate: date))) } /** Gets recieved push-notification from `GMSInboxFetchedDate` - Parameter date: `NSTimeInterval` concrete time interval *since 00:00:00 UTC on 1 January 2001* for which you need to get messages - Returns: An array of recieved `GlobalMessageServiceMessage`s */ public class func getPushNotifications(forDate date: NSTimeInterval) -> [GlobalMessageServiceMessage] { if let fetchedDate = GMSInboxFetchedDate.getInboxFetchedDate(forDate: date) { return synchronized(fetchedDate) { () -> [GlobalMessageServiceMessage] in if let messages = fetchedDate.messages?.allObjects as? [GMSInboxMessage] { return messages .filter { $0.type == GlobalMessageServiceMessageType.PushNotification.rawValue } .flatMap { GlobalMessageServiceMessage(message: $0) } } return [] } } return [] } /** Fetches messages of concrete type from Global Message Services servers - Parameter type: `GlobalMessageServiceMessageType` concrete type of messages which you need to get - Parameter date: `NSTimeInterval` concrete time interval *since 00:00:00 UTC on 1 January 2001* for which you need to get messages - Parameter completionHandler: The code to be executed once the request has finished. (optional). This block takes no parameters. Returns `Result` `<[GlobalMessageServiceMessage], GlobalMessageServiceError>`, where `result.value` is always contains `Array<GMSMessage>` if there no error occurred, otherwise see `result.error` */ private class func fetch( type: GlobalMessageServiceMessageType, date: NSTimeInterval, completionHandler completion: (GlobalMessageServiceResult<[GlobalMessageServiceMessage]>) -> Void) // swiftlint:disable:this line_length { let errorCompletion: (GlobalMessageServiceError) -> Void = { error in completion(.Failure(error)) } let gmsToken = GlobalMessageService.registeredGMStoken if gmsToken <= 0 { errorCompletion(.GMSTokenIsNotSet) return } guard let phone = GlobalMessageService.registeredUserPhone else { errorCompletion(.MessageFetcherError(.NoPhone)) return } let urlString: String = "requestMessages/" + type.requestSuffix() let timeInterval = UInt64( floor( NSDate(timeIntervalSinceReferenceDate: date).timeIntervalSince1970 * 1000)) let parameters: [String: AnyObject] = [ "uniqAppDeviceId": NSNumber(unsignedLongLong: gmsToken), "phone": NSNumber(longLong: phone), "date_utc": NSNumber(unsignedLongLong: timeInterval) ] let requestTime = NSDate().timeIntervalSinceReferenceDate let completionHandler = messagesFetchHandler( type, date: date, requestTime: requestTime, completionHandler: completion) GMSProvider.sharedInstance.POST( .OTTPlatform, urlString, parameters: parameters, checkStatus: false, completionHandler: completionHandler ) } /** Fetches messages of concrete type from Global Message Services servers - Parameter type: `GlobalMessageServiceMessageType` concrete type of messages which you need to get - Parameter date: `NSTimeInterval` concrete time interval *since 00:00:00 UTC on 1 January 2001* for which you need to get messages - Parameter requestTime: `NSTimeInterval` *since 00:00:00 UTC on 1 January 2001* when request was sended - Parameter completionHandler: The code to be executed once the request has finished. (optional). This block takes no parameters. Returns `Result` `<[GlobalMessageServiceMessage], GlobalMessageServiceError>`, where `result.value` is always contains `Array<GMSMessage>` if there no error occurred, otherwise see `result.error` - Returns: Closure that fetches messages and saves it to CodeData DB and executes passed `completionHandler` with result */ private class func messagesFetchHandler( type: GlobalMessageServiceMessageType, date: NSTimeInterval, requestTime: NSTimeInterval, completionHandler completion: (GlobalMessageServiceResult<[GlobalMessageServiceMessage]>) -> Void) -> (GlobalMessageServiceResult<[String : AnyObject]>) -> Void // swiftlint:disable:this line_length { return { response in guard let fullJSON: [String : AnyObject] = response.value(completion) else { return } guard let incomeMessages = fullJSON["messages"] as? [[String: AnyObject]] else { completion(.Success([])) return } let messages = incomeMessages .flatMap { GlobalMessageServiceMessage(dictionary: $0, andType: type) } GlobalMessageServiceMessagesFetcher.saveMessages( messages, date: date, requestTime: requestTime, completionHandler: completion) } } /** Fetches messages of concrete type from Global Message Services servers - Parameter messages: `[GlobalMessageServiceMessage]` an array of recieved messages - Parameter date: `NSTimeInterval` concrete date for which you need to get messages - Parameter requestTime: `NSTimeInterval` *since 00:00:00 UTC on 1 January 2001* when request was sended - Parameter completionHandler: The code to be executed once the request has finished. (optional). This block takes no parameters. Returns `Result` `<[GlobalMessageServiceMessage], GlobalMessageServiceError>`, where `result.value` is always contains `Array<GMSMessage>` if there no error occurred, otherwise see `result.error` */ private class func saveMessages( messages: [GlobalMessageServiceMessage], date: NSTimeInterval, requestTime: NSTimeInterval, completionHandler completion: (GlobalMessageServiceResult<[GlobalMessageServiceMessage]>) -> Void) // swiftlint:disable:this line_length { let managedObjectContext = GlobalMessageServiceCoreDataHelper.newManagedObjectContext() var deletedMessages = [GlobalMessageServiceMessage]() messages.forEach() { message in guard let coreDataMessage = GMSInboxMessage.findObject( withPredicate: NSPredicate(format: "messageID == %@", NSDecimalNumber(unsignedLongLong: message.id)), inManagedObjectContext: managedObjectContext) as? GMSInboxMessage else { return } coreDataMessage.messageID = NSDecimalNumber(unsignedLongLong: message.id) coreDataMessage.message = message.message coreDataMessage.deliveredDate = message.deliveredDate.timeIntervalSinceReferenceDate coreDataMessage.type = message.type.rawValue coreDataMessage.setAlphaNameString(message.alphaName) coreDataMessage.setFethcedDate() if coreDataMessage.deletionMark { deletedMessages.append(message) } } if messages.isEmpty { let fetchedDate = GMSInboxFetchedDate.getInboxFetchedDate( forDate: date, inManagedObjectContext: managedObjectContext, createNewIfNotFound: true) //let date = NSDate(timeIntervalSinceReferenceDate: date) if let fetchedDate = fetchedDate { if date == NSDate().startOfDay().timeIntervalSinceReferenceDate { fetchedDate.lastMessageDate = requestTime } else if date > NSDate().endOfDay().timeIntervalSinceReferenceDate { fetchedDate.lastMessageDate = NSDate(timeIntervalSinceReferenceDate: date) .startOfDay().timeIntervalSinceReferenceDate } else { fetchedDate.lastMessageDate = NSDate(timeIntervalSinceReferenceDate: date) .endOfDay() .timeIntervalSinceReferenceDate } } } let result = managedObjectContext.saveSafeRecursively() switch result { case .Failure(let error): completion(.Failure(.MessageFetcherError(.CoreDataSaveError(error as NSError)))) break case .Success: completion(.Success(messages.filter { deletedMessages.indexOf($0) == .None })) break } } }
apache-2.0
3270ea7615a730827fcf1d89279443d5
38.762431
140
0.702862
5.190768
false
false
false
false
Brightify/Cuckoo
Source/MockManager.swift
2
17427
// // MockManager.swift // Cuckoo // // Created by Filip Dolnik on 29.05.16. // Copyright © 2016 Brightify. All rights reserved. // import XCTest #if !swift(>=4.1) private extension Array { func compactMap<O>(_ transform: (Element) -> O?) -> [O] { return self.flatMap(transform) } } #endif public class MockManager { public static var fail: ((message: String, sourceLocation: SourceLocation)) -> () = { (arg) in let (message, sourceLocation) = arg; XCTFail(message, file: sourceLocation.file, line: sourceLocation.line) } private var stubs: [Stub] = [] private var stubCalls: [StubCall] = [] private var unverifiedStubCallsIndexes: [Int] = [] // TODO Add either enum or OptionSet for these behavior modifiers and add proper validation private var isSuperclassSpyEnabled = false private var isDefaultImplementationEnabled = false private let hasParent: Bool private let queue = DispatchQueue(label: "cuckoo-mockmanager") public init(hasParent: Bool) { self.hasParent = hasParent } private func callInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () -> OUT, defaultCall: () -> OUT) -> OUT { return callRethrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) private func callInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () async -> OUT, defaultCall: () async -> OUT) async -> OUT { return await callRethrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } private func callRethrowsInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () throws -> OUT, defaultCall: () throws -> OUT) rethrows -> OUT { let stubCall = ConcreteStubCall(method: method, parameters: escapingParameters) queue.sync { stubCalls.append(stubCall) unverifiedStubCallsIndexes.append(stubCalls.count - 1) } if let stub = (stubs.filter { $0.method == method }.compactMap { $0 as? ConcreteStub<IN, OUT> }.filter { $0.parameterMatchers.reduce(true) { $0 && $1.matches(parameters) } }.first) { guard let action = queue.sync(execute: { return stub.actions.count > 1 ? stub.actions.removeFirst() : stub.actions.first }) else { failAndCrash("Stubbing of method `\(method)` using parameters \(parameters) wasn't finished (missing thenReturn()).") } switch action { case .callImplementation(let implementation): return try DispatchQueue(label: "No-care?").sync(execute: { return try implementation(parameters) }) case .returnValue(let value): return value case .throwError(let error): return try DispatchQueue(label: "No-care?").sync(execute: { throw error }) case .callRealImplementation where hasParent: return try superclassCall() default: failAndCrash("No real implementation found for method `\(method)`. This is probably caused by stubbed object being a mock of a protocol.") } } else if isSuperclassSpyEnabled { return try superclassCall() } else if isDefaultImplementationEnabled { return try defaultCall() } else { failAndCrash("No stub for method `\(method)` using parameters \(parameters).") } } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) private func callRethrowsInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () async throws -> OUT, defaultCall: () async throws -> OUT) async rethrows -> OUT { let stubCall = ConcreteStubCall(method: method, parameters: escapingParameters) queue.sync { stubCalls.append(stubCall) unverifiedStubCallsIndexes.append(stubCalls.count - 1) } if let stub = (stubs.filter { $0.method == method }.compactMap { $0 as? ConcreteStub<IN, OUT> }.filter { $0.parameterMatchers.reduce(true) { $0 && $1.matches(parameters) } }.first) { guard let action = queue.sync(execute: { return stub.actions.count > 1 ? stub.actions.removeFirst() : stub.actions.first }) else { failAndCrash("Stubbing of method `\(method)` using parameters \(parameters) wasn't finished (missing thenReturn()).") } switch action { case .callImplementation(let implementation): return try DispatchQueue(label: "No-care?").sync(execute: { return try implementation(parameters) }) case .returnValue(let value): return value case .throwError(let error): return try DispatchQueue(label: "No-care?").sync(execute: { throw error }) case .callRealImplementation where hasParent: return try await superclassCall() default: failAndCrash("No real implementation found for method `\(method)`. This is probably caused by stubbed object being a mock of a protocol.") } } else if isSuperclassSpyEnabled { return try await superclassCall() } else if isDefaultImplementationEnabled { return try await defaultCall() } else { failAndCrash("No stub for method `\(method)` using parameters \(parameters).") } } private func callThrowsInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () throws -> OUT, defaultCall: () throws -> OUT) throws -> OUT { let stubCall = ConcreteStubCall(method: method, parameters: escapingParameters) queue.sync { stubCalls.append(stubCall) unverifiedStubCallsIndexes.append(stubCalls.count - 1) } if let stub = (stubs.filter { $0.method == method }.compactMap { $0 as? ConcreteStub<IN, OUT> }.filter { $0.parameterMatchers.reduce(true) { $0 && $1.matches(parameters) } }.first) { guard let action = queue.sync(execute: { return stub.actions.count > 1 ? stub.actions.removeFirst() : stub.actions.first }) else { failAndCrash("Stubbing of method `\(method)` using parameters \(parameters) wasn't finished (missing thenReturn()).") } switch action { case .callImplementation(let implementation): return try implementation(parameters) case .returnValue(let value): return value case .throwError(let error): throw error case .callRealImplementation where hasParent: return try superclassCall() default: failAndCrash("No real implementation found for method `\(method)`. This is probably caused by stubbed object being a mock of a protocol.") } } else if isSuperclassSpyEnabled { return try superclassCall() } else if isDefaultImplementationEnabled { return try defaultCall() } else { failAndCrash("No stub for method `\(method)` using parameters \(parameters).") } } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) private func callThrowsInternal<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: () async throws -> OUT, defaultCall: () async throws -> OUT) async throws -> OUT { let stubCall = ConcreteStubCall(method: method, parameters: escapingParameters) queue.sync { stubCalls.append(stubCall) unverifiedStubCallsIndexes.append(stubCalls.count - 1) } if let stub = (stubs.filter { $0.method == method }.compactMap { $0 as? ConcreteStub<IN, OUT> }.filter { $0.parameterMatchers.reduce(true) { $0 && $1.matches(parameters) } }.first) { guard let action = queue.sync(execute: { return stub.actions.count > 1 ? stub.actions.removeFirst() : stub.actions.first }) else { failAndCrash("Stubbing of method `\(method)` using parameters \(parameters) wasn't finished (missing thenReturn()).") } switch action { case .callImplementation(let implementation): return try implementation(parameters) case .returnValue(let value): return value case .throwError(let error): throw error case .callRealImplementation where hasParent: return try await superclassCall() default: failAndCrash("No real implementation found for method `\(method)`. This is probably caused by stubbed object being a mock of a protocol.") } } else if isSuperclassSpyEnabled { return try await superclassCall() } else if isDefaultImplementationEnabled { return try await defaultCall() } else { failAndCrash("No stub for method `\(method)` using parameters \(parameters).") } } public func createStub<MOCK: ClassMock, IN, OUT>(for _: MOCK.Type, method: String, parameterMatchers: [ParameterMatcher<IN>]) -> ClassConcreteStub<IN, OUT> { let stub = ClassConcreteStub<IN, OUT>(method: method, parameterMatchers: parameterMatchers) stubs.insert(stub, at: 0) return stub } public func createStub<MOCK: ProtocolMock, IN, OUT>(for _: MOCK.Type, method: String, parameterMatchers: [ParameterMatcher<IN>]) -> ConcreteStub<IN, OUT> { let stub = ConcreteStub<IN, OUT>(method: method, parameterMatchers: parameterMatchers) stubs.insert(stub, at: 0) return stub } public func verify<IN, OUT>(_ method: String, callMatcher: CallMatcher, parameterMatchers: [ParameterMatcher<IN>], sourceLocation: SourceLocation) -> __DoNotUse<IN, OUT> { var calls: [StubCall] = [] var indexesToRemove: [Int] = [] for (i, stubCall) in stubCalls.enumerated() { if let stubCall = stubCall as? ConcreteStubCall<IN> , (parameterMatchers.reduce(stubCall.method == method) { $0 && $1.matches(stubCall.parameters) }) { calls.append(stubCall) indexesToRemove.append(i) } } unverifiedStubCallsIndexes = unverifiedStubCallsIndexes.filter { !indexesToRemove.contains($0) } if callMatcher.matches(calls) == false { let message = "Wanted \(callMatcher.name) but \(calls.count == 0 ? "not invoked" : "invoked \(calls.count) times")." MockManager.fail((message, sourceLocation)) } return __DoNotUse() } public func enableSuperclassSpy() { guard stubCalls.isEmpty else { failAndCrash("Enabling superclass spy is not allowed after stubbing! Please do that right after creating the mock.") } guard !isDefaultImplementationEnabled else { failAndCrash("Enabling superclass spy is not allowed with the default stub implementation enabled.") } isSuperclassSpyEnabled = true } public func enableDefaultStubImplementation() { guard stubCalls.isEmpty else { failAndCrash("Enabling default stub implementation is not allowed after stubbing! Please do that right after creating the mock.") } guard !isSuperclassSpyEnabled else { failAndCrash("Enabling default stub implementation is not allowed with superclass spy enabled.") } isDefaultImplementationEnabled = true } func reset() { clearStubs() clearInvocations() } func clearStubs() { stubs.removeAll() } func clearInvocations() { queue.sync { stubCalls.removeAll() unverifiedStubCallsIndexes.removeAll() } } func verifyNoMoreInteractions(_ sourceLocation: SourceLocation) { if unverifiedStubCallsIndexes.isEmpty == false { let unverifiedCalls = unverifiedStubCallsIndexes.map { stubCalls[$0] }.map { call in if let bracketIndex = call.method.range(of: "(")?.lowerBound { let name = call.method[..<bracketIndex] return name + call.parametersAsString } else { if call.method.hasSuffix("#set") { return call.method + call.parametersAsString } else { return call.method } } }.enumerated().map { "\($0 + 1). " + $1 }.joined(separator: "\n") let message = "No more interactions wanted but some found:\n" MockManager.fail((message + unverifiedCalls, sourceLocation)) } } private func failAndCrash(_ message: String, file: StaticString = #file, line: UInt = #line) -> Never { MockManager.fail((message, (file, line))) #if _runtime(_ObjC) NSException(name: .internalInconsistencyException, reason:message, userInfo: nil).raise() #endif fatalError(message) } } extension MockManager { public static func callOrCrash<T, OUT>(_ value: T?, call: (T) throws -> OUT) rethrows -> OUT { guard let value = value else { return crashOnProtocolSuperclassCall() } return try call(value) } public static func crashOnProtocolSuperclassCall<OUT>() -> OUT { fatalError("This should never get called. If it does, please report an issue to Cuckoo repository.") } } extension MockManager { public func getter<T>(_ property: String, superclassCall: @autoclosure () -> T, defaultCall: @autoclosure () -> T) -> T { return call(getterName(property), parameters: Void(), escapingParameters: Void(), superclassCall: superclassCall(), defaultCall: defaultCall()) } public func setter<T>(_ property: String, value: T, superclassCall: @autoclosure () -> Void, defaultCall: @autoclosure () -> Void) { return call(setterName(property), parameters: value, escapingParameters: value, superclassCall: superclassCall(), defaultCall: defaultCall()) } } extension MockManager { public func call<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () -> OUT, defaultCall: @autoclosure () -> OUT) -> OUT { return callInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func call<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () async -> OUT, defaultCall: @autoclosure () async -> OUT) async -> OUT { return await callInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } } extension MockManager { public func callThrows<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () throws -> OUT, defaultCall: @autoclosure () throws -> OUT) throws -> OUT { return try callThrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func callThrows<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () async throws -> OUT, defaultCall: @autoclosure () async throws -> OUT) async throws -> OUT { return try await callThrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } } extension MockManager { public func callRethrows<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () throws -> OUT, defaultCall: @autoclosure () throws -> OUT) rethrows -> OUT { return try callRethrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func callRethrows<IN, OUT>(_ method: String, parameters: IN, escapingParameters: IN, superclassCall: @autoclosure () async throws -> OUT, defaultCall: @autoclosure () async throws -> OUT) async rethrows -> OUT { return try await callRethrowsInternal(method, parameters: parameters, escapingParameters: escapingParameters, superclassCall: superclassCall, defaultCall: defaultCall) } }
mit
87259aa7b58bfa035682223a8fb3be59
48.931232
222
0.630265
4.718657
false
false
false
false
alessioros/mobilecodegenerator3
examples/ParkTraining/generated/ios/ParkTraining/ParkTraining/LocationEditViewController.swift
2
2756
import UIKit import MapKit class LocationEditViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var deleteLocationButton: UIButton! @IBOutlet weak var mMap: MKMapView! override func viewDidLoad() { super.viewDidLoad() deleteLocationButton.layer.cornerRadius = 40 self.mMap.delegate = self let lat = 45.478 let lon = 9.227 let coordinates = CLLocationCoordinate2D(latitude: lat, longitude: lon) let region = MKCoordinateRegionMake(CLLocationCoordinate2DMake(lat, lon), MKCoordinateSpanMake(0.005, 0.005)) let annotation = MKPointAnnotation() annotation.coordinate = coordinates annotation.title = "MARKER TITLE HERE" self.mMap.setRegion(region, animated: true) self.mMap.addAnnotation(annotation) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //Create the AlertController let deleteLocationDialog: UIAlertController = UIAlertController(title: "Delete Location", message: "Are you sure?", preferredStyle: .Alert) //Create and add the Cancel action let deleteLocationDialogCancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in //Just dismiss the alert } //Create and add the Ok action let deleteLocationDialogOkAction: UIAlertAction = UIAlertAction(title: "Ok", style: .Default) { action -> Void in //Do some stuff here } deleteLocationDialog.addAction(deleteLocationDialogCancelAction) deleteLocationDialog.addAction(deleteLocationDialogOkAction) //Present the AlertController self.presentViewController(deleteLocationDialog, animated: true, completion: nil) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } @IBAction func deleteLocationButtonTouchDown(sender: UIButton) { // Changes background color of button when clicked sender.backgroundColor = UIColor(red: 0.7019608, green: 0.019607844, blue: 0.019607844, alpha: 1) //TODO Implement the action } @IBAction func deleteLocationButtonTouchUpInside(sender: UIButton) { // Restore original background color of button after click sender.backgroundColor = UIColor(red: 0.8, green: 0.0, blue: 0.0, alpha: 1) //TODO Implement the action } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } }
gpl-3.0
e88cdf8957a7f17d0840b7227d9bca6b
26.56
141
0.728229
4.459547
false
false
false
false
el-hoshino/NotAutoLayout
Playground.playground/Sources/ProfileSummaryView.swift
1
2850
import UIKit import NotAutoLayout public class ProfileSummaryView: UIView { private let avatarView: UIImageView private let mainTitleLabel: UILabel private let subTitleLabel: UILabel public var avatar: UIImage? { get { return self.avatarView.image } set { self.avatarView.image = newValue } } public var mainTitle: String? { get { return self.mainTitleLabel.text } set { self.mainTitleLabel.text = newValue } } public var subTitle: String? { get { return self.subTitleLabel.text } set { self.subTitleLabel.text = newValue } } public override init(frame: CGRect) { self.avatarView = UIImageView() self.mainTitleLabel = UILabel() self.subTitleLabel = UILabel() super.init(frame: frame) self.setupAvatarView() self.setupMainTitleView() self.setupSubTitleView() } public convenience init() { self.init(frame: .zero) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func layoutSubviews() { super.layoutSubviews() self.placeAvatarView() self.placeMainTitleView() self.placeSubTitleView() } } extension ProfileSummaryView { private func setupAvatarView() { let view = self.avatarView view.backgroundColor = .red view.clipsToBounds = true self.addSubview(view) } private func setupMainTitleView() { let view = self.mainTitleLabel view.clipsToBounds = true view.font = .boldSystemFont(ofSize: UIFont.smallSystemFontSize) view.textColor = .black self.addSubview(view) } private func setupSubTitleView() { let view = self.subTitleLabel view.clipsToBounds = true view.font = .systemFont(ofSize: UIFont.smallSystemFontSize) view.textColor = .darkGray self.addSubview(view) } } extension ProfileSummaryView { private func placeAvatarView() { self.nal.layout(self.avatarView) { $0 .setTopLeft(by: { $0.layoutMarginsGuide.topLeft }) .setSize(by: { let length = min($0.layoutMarginsGuide.width, $0.safeAreaGuide.height); return .init(width: length, height: length) }) .addingProcess(by: { (frame, parameters) in parameters.targetView.layer.cornerRadius = (min(frame.width, frame.height) / 2).cgValue }) } } private func placeMainTitleView() { self.nal.layout(self.mainTitleLabel, by: { $0 .pinTopLeft(to: self.avatarView, with: { $0.topRight }) .setRight(by: { $0.layoutMarginsGuide.right }) .setBottom(by: { $0.safeAreaGuide.middle }) .pinchingLeft(by: 10) }) } private func placeSubTitleView() { self.nal.layout(self.subTitleLabel) { $0 .pinTopLeft(to: self.mainTitleLabel, with: { $0.bottomLeft }) .pinRight(to: self.mainTitleLabel, with: { $0.right }) .setBottom(by: { $0.safeAreaGuide.top + $0.safeAreaGuide.height * 0.75 }) } } }
apache-2.0
81752c455da33383160905050cbea251
19.955882
136
0.693684
3.405018
false
false
false
false
carambalabs/UnsplashKit
UnsplashKit/Classes/UnsplashAPI/Models/Response.swift
1
1305
import Foundation /// API response that includes the pagination links. public struct Response<A> { // MARK: - Attributes /// Response object. public let object: A /// Pagination first link. public let firstLink: Link? /// Pagination previous link. public let prevLink: Link? /// Pagination next link. public let nextLink: Link? /// Pagination last link. public let lastLink: Link? /// Limit of requests. public let limitRequests: Int? /// Number of remaining requests. public let remainingRequests: Int? // MARK: - Init /// Initializes the response with the object and the http response. /// /// - Parameters: /// - object: object included in the response. /// - response: http url response. internal init(object: A, response: HTTPURLResponse) { self.object = object self.firstLink = response.findLink(relation: "first") self.prevLink = response.findLink(relation: "prev") self.nextLink = response.findLink(relation: "next") self.lastLink = response.findLink(relation: "last") self.limitRequests = response.allHeaderFields["X-Ratelimit-Limit"] as? Int self.remainingRequests = response.allHeaderFields["X-Ratelimit-Remaining"] as? Int } }
mit
156cd902e951dbe91b8c5ae6ea94faeb
27.369565
91
0.65364
4.321192
false
false
false
false
ppraveentr/MobileCore
Example/MobileCoreExample/Classes/ContentViewController.swift
1
1040
// // ContentViewController.swift // MobileCore // // Created by Praveen P on 01/11/19. // Copyright © 2019 Praveen Prabhakar. All rights reserved. // import Foundation #if canImport(AppTheming) import AppTheming import CoreComponents #endif final class ContentViewController: UIViewController, WebViewControllerProtocol { let value = """ <p>1) Follow @ppraveentr or #visit <a href=\"www.W3Schools.com\">Visit W3Schools</a></p> <p>2) Follow @ppraveentr or #visit <a href=\"www.W3Schools.com\">Visit W3Schools</a></p> <p>3) Follow @ppraveentr or #visit <a href=\"www.W3Schools.com\">Visit W3Schools</a></p> <p>4) Follow @ppraveentr or #visit <a href=\"www.W3Schools.com\">Visit W3Schools</a></p> <p>5) Follow @ppraveentr or #visit <a href=\"www.W3Schools.com\">Visit W3Schools</a></p> """ override func viewDidLoad() { super.viewDidLoad() // Setup MobileCore setupCoreView() // Load HTLM contentView.loadHTMLBody(value) } }
mit
e1bfc0baa91a446bcb8b209678b38c10
31.46875
96
0.647738
3.308917
false
false
false
false
DivineDominion/mac-appdev-code
DDDViewDataExample/ManagedItem.swift
1
2562
import Foundation import CoreData private var itemContext = 0 @objc(ManagedItem) open class ManagedItem: NSManagedObject, ManagedEntity { @NSManaged open var uniqueId: NSNumber @NSManaged open var title: String @NSManaged open var creationDate: Date @NSManaged open var modificationDate: Date @NSManaged open var box: ManagedBox open static var entityName: String { return "ManagedItem" } open static func insertManagedItem(_ item: Item, managedBox: ManagedBox, inManagedObjectContext managedObjectContext:NSManagedObjectContext) { let managedItem: ManagedItem = self.create(into: managedObjectContext) managedItem.item = item managedItem.box = managedBox } static func uniqueIdFromItemId(_ itemId: ItemId) -> NSNumber { return NSNumber(value: itemId.identifier as Int64) } open func itemId() -> ItemId { return ItemId(self.uniqueId.int64Value) } //MARK: - //MARK: Item Management fileprivate var _item: Item? open var item: Item { get { if let item = _item { return item } let item = Item(itemId: self.itemId(), title: self.title) // TODO add back-reference to box observe(item) _item = item return item } set { precondition(!hasValue(_item), "can be set only before lazy initialization of item") let item = newValue adapt(item) observe(item) _item = item } } func observe(_ item: Item) { item.addObserver(self, forKeyPath: "title", options: .new, context: &itemContext) } func adapt(_ item: Item) { uniqueId = ManagedItem.uniqueIdFromItemId(item.itemId) title = item.title } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context != &itemContext { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } if keyPath == "title" { self.title = change?[NSKeyValueChangeKey.newKey] as! String } } deinit { if let item = _item { item.removeObserver(self, forKeyPath: "title") } } }
mit
7932367cfd128cd80f24a3d4288c1bca
26.847826
156
0.57338
5.003906
false
false
false
false
leotao2014/RTPhotoBrowser
RTPhotoBrowser/RTProgressView.swift
1
2223
// // RTProgressView.swift // RTPhotoBrowser // // Created by leotao on 2017/5/7. // Copyright © 2017年 leotao. All rights reserved. // import UIKit let kProgressViewWidth:CGFloat = 60; class RTProgressView: UIView { var progress:CGFloat = 0.0 { didSet { setupLayer(withProgress: progress); } } var backgroundLayer = { () -> CAShapeLayer in let layer = CAShapeLayer(); layer.strokeColor = UIColor.white.cgColor; layer.fillColor = UIColor.black.withAlphaComponent(0.5).cgColor; return layer; }(); var progressLayer = { () -> CAShapeLayer in let layer = CAShapeLayer(); layer.strokeColor = UIColor.clear.cgColor; layer.fillColor = UIColor.white.cgColor; return layer; }(); init() { super.init(frame: .zero); self.layer.addSublayer(backgroundLayer); self.layer.addSublayer(progressLayer); } override func layoutSubviews() { super.layoutSubviews(); backgroundLayer.frame = self.bounds; progressLayer.frame = self.bounds; } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupLayer(withProgress progress:CGFloat) { if self.bounds.size == .zero { return; } let bgPath = UIBezierPath(); let center = CGPoint(x: self.bounds.width * 0.5, y: self.bounds.height * 0.5); let radius = self.bounds.width * 0.5; bgPath.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(.pi * 2.0), clockwise: true); backgroundLayer.path = bgPath.cgPath; let progressPath = UIBezierPath(); let progressRadius = radius - 2.5; progressPath.move(to: center); progressPath.addArc(withCenter: center, radius: progressRadius, startAngle: -(.pi / 2.0), endAngle: (2.0 * progress - 0.5) * .pi, clockwise: true); progressLayer.path = progressPath.cgPath; } } extension RTProgressView: RTProgressViewDelegate { func rt_setProgress(progress: CGFloat) { self.progress = progress; } }
apache-2.0
2b4f3f592e349dd25704a64301b65167
28.6
155
0.609009
4.319066
false
false
false
false
heyjessi/SafeWays
SafeWayController/AppDelegate.swift
1
3266
// // AppDelegate.swift // SafeWay // // Created by Hansen Qian on 7/11/15. // Copyright (c) 2015 HQ. All rights reserved. // import GoogleMaps import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // !! Do not share this key! !! GMSServices .provideAPIKey("AIzaSyByf93DyY9g-sezZBVIKJKQ4_2Q4M57dqQ") UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: .Fade) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.backgroundColor = UIColor.whiteColor() self.window?.makeKeyAndVisible() // let tbc = UITabBarController() // // let tbiInput = UITabBarItem(tabBarSystemItem: .Search, tag: 0) // let vcInput = InputViewController() //// let vcNav = UINavigationController(rootViewController: vcInput) //// vcNav.navigationBarHidden = true // vcInput.tbc = tbc // vcInput.tabBarItem = tbiInput // // let tbiMap = UITabBarItem(tabBarSystemItem: .Bookmarks, tag: 1) // let vcMap = MapViewController() // vcMap.tabBarItem = tbiMap // vcInput.mvc = vcMap // // let tbiMap2 = UITabBarItem(tabBarSystemItem: .History, tag: 2) let vcMap2 = EntireMapView() // vcMap2.tabBarItem = tbiMap2 // // tbc.viewControllers = [vcInput, vcMap, vcMap2] self.window?.rootViewController = vcMap2 return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
ed7c6768d4b90c89fe2679581305a6da
42.546667
285
0.714023
4.747093
false
false
false
false
jbrayton/Golden-Hill-HTTP-Library
GoldenHillHTTPLibrary/URLRequest+Convenience.swift
1
1358
// // URLRequest+Convenience.swift // GoldenHillHTTPLibrary // // Created by John Brayton on 3/1/17. // Copyright © 2017 John Brayton. All rights reserved. // import Foundation public extension URLRequest { mutating func ghs_setPostJson(_ jsonDictionary: [String: Any]) { do { self.setValue("application/json", forHTTPHeaderField: "Content-Type") self.httpMethod = "POST" let data = try JSONSerialization.data(withJSONObject: jsonDictionary, options: JSONSerialization.WritingOptions()) self.httpBody = data } catch { NSLog("Unable to set POST json") } } mutating func ghs_setPostArgString( _ value: String ) { self.httpMethod = "POST" self.httpBody = value.data(using: String.Encoding.utf8) } mutating func ghs_setBasicAuth( username: String, password: String ) { let str = String(format: "%@:%@", arguments: [username, password]) let data = str.data(using: String.Encoding.utf8)! let base64 = data.base64EncodedData(options: NSData.Base64EncodingOptions()) let base64String = String(data: base64, encoding: String.Encoding.utf8)! let headerValue = String(format: "Basic %@", base64String) self.setValue(headerValue, forHTTPHeaderField: "Authorization") } }
mit
13644819f4d2206300a2c2ae7fd32377
34.710526
126
0.647752
4.294304
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/Raster layer (geopackage)/RasterLayerGPKGViewController.swift
1
2109
// Copyright 2017 Esri. // // 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 ArcGIS class RasterLayerGPKGViewController: UIViewController { @IBOutlet weak var mapView: AGSMapView! var geoPackage: AGSGeoPackage? override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["RasterLayerGPKGViewController"] // Instantiate a map. let map = AGSMap(basemapStyle: .arcGISLightGrayBase) // Create a geopackage from a named bundle resource. geoPackage = AGSGeoPackage(name: "AuroraCO") // Load the geopackage. geoPackage?.load { [weak self] error in guard error == nil else { self?.presentAlert(message: "Error opening Geopackage: \(error!.localizedDescription)") return } // Add the first raster from the geopackage to the map. if let raster = self?.geoPackage?.geoPackageRasters.first { let rasterLayer = AGSRasterLayer(raster: raster) // make it semi-transparent so it doesn't obscure the contents under it rasterLayer.opacity = 0.55 map.operationalLayers.add(rasterLayer) } } // Display the map in the map view. mapView.map = map mapView.setViewpoint(AGSViewpoint(latitude: 39.7294, longitude: -104.8319, scale: 288895.277144)) } }
apache-2.0
fbb47be2a34537c0adf98ee376085eeb
38.055556
122
0.650071
4.625
false
false
false
false
yonaskolb/XcodeGen
Tests/XcodeGenKitTests/ProjectGeneratorTests.swift
1
159136
import PathKit import ProjectSpec import Spectre import XcodeGenKit import XcodeProj import XCTest import Yams import TestSupport private let app = Target( name: "MyApp", type: .application, platform: .iOS, settings: Settings(buildSettings: ["SETTING_1": "VALUE"]), dependencies: [Dependency(type: .target, reference: "MyFramework")] ) private let framework = Target( name: "MyFramework", type: .framework, platform: .iOS, settings: Settings(buildSettings: ["SETTING_2": "VALUE"]) ) private let optionalFramework = Target( name: "MyOptionalFramework", type: .framework, platform: .iOS ) private let uiTest = Target( name: "MyAppUITests", type: .uiTestBundle, platform: .iOS, settings: Settings(buildSettings: ["SETTING_3": "VALUE"]), dependencies: [Dependency(type: .target, reference: "MyApp")] ) private let targets = [app, framework, optionalFramework, uiTest] class ProjectGeneratorTests: XCTestCase { func testOptions() throws { describe { $0.it("generates bundle id") { let options = SpecOptions(bundleIdPrefix: "com.test") let project = Project(name: "test", targets: [framework], options: options) let pbxProj = try project.generatePbxProj() guard let target = pbxProj.nativeTargets.first, let buildConfigList = target.buildConfigurationList, let buildConfig = buildConfigList.buildConfigurations.first else { throw failure("Build Config not found") } try expect(buildConfig.buildSettings["PRODUCT_BUNDLE_IDENTIFIER"] as? String) == "com.test.MyFramework" } $0.it("clears setting presets") { let options = SpecOptions(settingPresets: .none) let project = Project(name: "test", targets: [framework], options: options) let pbxProj = try project.generatePbxProj() let allSettings = pbxProj.buildConfigurations.reduce([:]) { $0.merged($1.buildSettings) }.keys.sorted() try expect(allSettings) == ["SDKROOT", "SETTING_2"] } $0.it("generates development language") { let options = SpecOptions(developmentLanguage: "de") let project = Project(name: "test", options: options) let pbxProj = try project.generatePbxProj() let pbxProject = try unwrap(pbxProj.projects.first) try expect(pbxProject.developmentRegion) == "de" } $0.it("formats xcode version") { let versions: [String: String] = [ "0900": "0900", "1010": "1010", "9": "0900", "9.0": "0900", "9.1": "0910", "9.1.1": "0911", "10": "1000", "10.1": "1010", "10.1.2": "1012", ] for (version, expected) in versions { try expect(XCodeVersion.parse(version)) == expected } } $0.it("uses the default configuration name") { let options = SpecOptions(defaultConfig: "Bconfig") let project = Project(name: "test", configs: [Config(name: "Aconfig"), Config(name: "Bconfig")], targets: [framework], options: options) let pbxProject = try project.generatePbxProj() guard let projectConfigList = pbxProject.projects.first?.buildConfigurationList, let defaultConfigurationName = projectConfigList.defaultConfigurationName else { throw failure("Default configuration name not found") } try expect(defaultConfigurationName) == "Bconfig" } $0.it("uses the default configuration name for every target in a project") { let options = SpecOptions(defaultConfig: "Bconfig") let project = Project( name: "test", configs: [ Config(name: "Aconfig"), Config(name: "Bconfig"), ], targets: [ Target(name: "1", type: .framework, platform: .iOS), Target(name: "2", type: .framework, platform: .iOS), ], options: options ) let pbxProject = try project.generatePbxProj() try pbxProject.projects.first?.targets.forEach { target in guard let buildConfigurationList = target.buildConfigurationList, let defaultConfigurationName = buildConfigurationList.defaultConfigurationName else { throw failure("Default configuration name not found") } try expect(defaultConfigurationName) == "Bconfig" } } } } func testConfigGenerator() { describe { $0.it("generates config defaults") { let project = Project(name: "test") let pbxProj = try project.generatePbxProj() let configs = pbxProj.buildConfigurations try expect(configs.count) == 2 try expect(configs).contains(name: "Debug") try expect(configs).contains(name: "Release") } $0.it("generates configs") { let project = Project( name: "test", configs: [Config(name: "config1"), Config(name: "config2")] ) let pbxProj = try project.generatePbxProj() let configs = pbxProj.buildConfigurations try expect(configs.count) == 2 try expect(configs).contains(name: "config1") try expect(configs).contains(name: "config2") } $0.it("clears config settings when missing type") { let project = Project( name: "test", configs: [Config(name: "config")] ) let pbxProj = try project.generatePbxProj() let config = try unwrap(pbxProj.buildConfigurations.first) try expect(config.buildSettings.isEmpty).to.beTrue() } $0.it("merges settings") { let project = try Project(path: fixturePath + "settings_test.yml") let config = try unwrap(project.getConfig("config1")) let debugProjectSettings = project.getProjectBuildSettings(config: config) let target = try unwrap(project.getTarget("Target")) let targetDebugSettings = project.getTargetBuildSettings(target: target, config: config) var buildSettings = BuildSettings() buildSettings += ["SDKROOT": "iphoneos"] buildSettings += SettingsPresetFile.base.getBuildSettings() buildSettings += SettingsPresetFile.config(.debug).getBuildSettings() buildSettings += [ "SETTING": "value", "SETTING 5": "value 5", "SETTING 6": "value 6", ] try expect(debugProjectSettings.equals(buildSettings)).beTrue() var expectedTargetDebugSettings = BuildSettings() expectedTargetDebugSettings += SettingsPresetFile.platform(.iOS).getBuildSettings() expectedTargetDebugSettings += SettingsPresetFile.product(.application).getBuildSettings() expectedTargetDebugSettings += SettingsPresetFile.productPlatform(.application, .iOS).getBuildSettings() expectedTargetDebugSettings += ["SETTING 2": "value 2", "SETTING 3": "value 3", "SETTING": "value"] try expect(targetDebugSettings.equals(expectedTargetDebugSettings)).beTrue() } $0.it("applies partial config settings") { let project = Project( name: "test", configs: [ Config(name: "Release", type: .release), Config(name: "Staging Debug", type: .debug), Config(name: "Staging Release", type: .release), ], settings: Settings(configSettings: [ "staging": ["SETTING1": "VALUE1"], "debug": ["SETTING2": "VALUE2"], "Release": ["SETTING3": "VALUE3"], ]) ) var buildSettings = project.getProjectBuildSettings(config: project.configs[1]) try expect(buildSettings["SETTING1"] as? String) == "VALUE1" try expect(buildSettings["SETTING2"] as? String) == "VALUE2" // don't apply partial when exact match buildSettings = project.getProjectBuildSettings(config: project.configs[2]) try expect(buildSettings["SETTING3"]).beNil() } $0.it("sets project SDKROOT if there is only a single platform") { var project = Project( name: "test", targets: [ Target(name: "1", type: .application, platform: .iOS), Target(name: "2", type: .framework, platform: .iOS), ] ) var buildSettings = project.getProjectBuildSettings(config: project.configs.first!) try expect(buildSettings["SDKROOT"] as? String) == "iphoneos" project.targets.append(Target(name: "3", type: .application, platform: .tvOS)) buildSettings = project.getProjectBuildSettings(config: project.configs.first!) try expect(buildSettings["SDKROOT"]).beNil() } } } func testAggregateTargets() { describe { let otherTarget = Target(name: "Other", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: "AggregateTarget")]) let otherTarget2 = Target(name: "Other2", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: "Other")], transitivelyLinkDependencies: true) let aggregateTarget = AggregateTarget(name: "AggregateTarget", targets: ["MyApp", "MyFramework"]) let aggregateTarget2 = AggregateTarget(name: "AggregateTarget2", targets: ["AggregateTarget"]) let project = Project(name: "test", targets: [app, framework, otherTarget, otherTarget2], aggregateTargets: [aggregateTarget, aggregateTarget2]) $0.it("generates aggregate targets") { let pbxProject = try project.generatePbxProj() let nativeTargets = pbxProject.nativeTargets.sorted { $0.name < $1.name } let aggregateTargets = pbxProject.aggregateTargets.sorted { $0.name < $1.name } try expect(nativeTargets.count) == 4 try expect(aggregateTargets.count) == 2 let aggregateTarget1 = aggregateTargets.first { $0.name == "AggregateTarget" } try expect(aggregateTarget1?.dependencies.count) == 2 let aggregateTarget2 = aggregateTargets.first { $0.name == "AggregateTarget2" } try expect(aggregateTarget2?.dependencies.count) == 1 let target1 = nativeTargets.first { $0.name == "Other" } try expect(target1?.dependencies.count) == 1 let target2 = nativeTargets.first { $0.name == "Other2" } try expect(target2?.dependencies.count) == 2 try expect(pbxProject.targetDependencies.count) == 7 } } } func testTargets() { describe { let project = Project(name: "test", targets: targets) $0.it("generates targets") { let pbxProject = try project.generatePbxProj() let nativeTargets = pbxProject.nativeTargets try expect(nativeTargets.count) == 4 try expect(nativeTargets.contains { $0.name == app.name }).beTrue() try expect(nativeTargets.contains { $0.name == framework.name }).beTrue() try expect(nativeTargets.contains { $0.name == uiTest.name }).beTrue() try expect(nativeTargets.contains { $0.name == optionalFramework.name }).beTrue() } $0.it("generates legacy target") { let target = Target(name: "target", type: .application, platform: .iOS, dependencies: [.init(type: .target, reference: "legacy")]) let legacyTarget = Target(name: "legacy", type: .none, platform: .iOS, legacy: .init(toolPath: "path")) let project = Project(name: "test", targets: [target, legacyTarget]) let pbxProject = try project.generatePbxProj() try expect(pbxProject.legacyTargets.count) == 1 } $0.it("generates target attributes") { var appTargetWithAttributes = app appTargetWithAttributes.settings.buildSettings["DEVELOPMENT_TEAM"] = "123" appTargetWithAttributes.attributes = ["ProvisioningStyle": "Automatic"] var testTargetWithAttributes = uiTest testTargetWithAttributes.settings.buildSettings["CODE_SIGN_STYLE"] = "Manual" let project = Project(name: "test", targets: [appTargetWithAttributes, framework, optionalFramework, testTargetWithAttributes]) let pbxProject = try project.generatePbxProj() let targetAttributes = try unwrap(pbxProject.projects.first?.targetAttributes) let appTarget = try unwrap(pbxProject.targets(named: app.name).first) let uiTestTarget = try unwrap(pbxProject.targets(named: uiTest.name).first) try expect((targetAttributes[uiTestTarget]?["TestTargetID"] as? PBXNativeTarget)?.name) == app.name try expect(targetAttributes[uiTestTarget]?["ProvisioningStyle"] as? String) == "Manual" try expect(targetAttributes[appTarget]?["ProvisioningStyle"] as? String) == "Automatic" try expect(targetAttributes[appTarget]?["DevelopmentTeam"] as? String) == "123" } $0.it("generates platform version") { let target = Target(name: "Target", type: .application, platform: .watchOS, deploymentTarget: "2.0") let project = Project(name: "", targets: [target], options: .init(deploymentTarget: DeploymentTarget(iOS: "10.0", watchOS: "3.0"))) let pbxProject = try project.generatePbxProj() let projectConfig = try unwrap(pbxProject.projects.first?.buildConfigurationList?.buildConfigurations.first) let targetConfig = try unwrap(pbxProject.nativeTargets.first?.buildConfigurationList?.buildConfigurations.first) try expect(projectConfig.buildSettings["IPHONEOS_DEPLOYMENT_TARGET"] as? String) == "10.0" try expect(projectConfig.buildSettings["WATCHOS_DEPLOYMENT_TARGET"] as? String) == "3.0" try expect(projectConfig.buildSettings["TVOS_DEPLOYMENT_TARGET"]).beNil() try expect(targetConfig.buildSettings["IPHONEOS_DEPLOYMENT_TARGET"]).beNil() try expect(targetConfig.buildSettings["WATCHOS_DEPLOYMENT_TARGET"] as? String) == "2.0" try expect(targetConfig.buildSettings["TVOS_DEPLOYMENT_TARGET"]).beNil() } $0.it("generates dependencies") { let pbxProject = try project.generatePbxProj() let nativeTargets = pbxProject.nativeTargets let dependencies = pbxProject.targetDependencies.sorted { $0.target?.name ?? "" < $1.target?.name ?? "" } try expect(dependencies.count) == 2 let appTarget = nativeTargets.first { $0.name == app.name } let frameworkTarget = nativeTargets.first { $0.name == framework.name } try expect(dependencies).contains { $0.target == appTarget } try expect(dependencies).contains { $0.target == frameworkTarget } } $0.it("generates dependency from external project file") { let subproject: PBXProj prepareXcodeProj: do { let project = try! Project(path: fixturePath + "TestProject/AnotherProject/project.yml") let generator = ProjectGenerator(project: project) let writer = FileWriter(project: project) let xcodeProject = try! generator.generateXcodeProject() try! writer.writeXcodeProject(xcodeProject) try! writer.writePlists() subproject = xcodeProject.pbxproj } let externalProjectPath = fixturePath + "TestProject/AnotherProject/AnotherProject.xcodeproj" let projectReference = ProjectReference(name: "AnotherProject", path: externalProjectPath.string) var target = app target.dependencies = [ Dependency(type: .target, reference: "AnotherProject/ExternalTarget"), ] let project = Project( name: "test", targets: [target], schemes: [], projectReferences: [projectReference] ) let pbxProject = try project.generatePbxProj() let projectReferences = pbxProject.rootObject?.projects ?? [] try expect(projectReferences.count) == 1 try expect((projectReferences.first?["ProjectRef"])?.name) == "AnotherProject" let dependencies = pbxProject.targetDependencies let targetUuid = subproject.targets(named: "ExternalTarget").first?.uuid try expect(dependencies.count) == 1 try expect(dependencies).contains { dependency in guard let id = dependency.targetProxy?.remoteGlobalID else { return false } switch id { case .object(let object): return object.uuid == targetUuid case .string(let value): return value == targetUuid } } } $0.it("generates targets with correct transitive embeds") { // App # Embeds it's frameworks, so shouldn't embed in tests // dependencies: // - framework: FrameworkA.framework // - framework: FrameworkB.framework // embed: false // iOSFrameworkZ: // dependencies: [] // iOSFrameworkX: // dependencies: [] // StaticLibrary: // dependencies: // - target: iOSFrameworkZ // - framework: FrameworkZ.framework // - carthage: CarthageZ // ResourceBundle // dependencies: [] // iOSFrameworkA // dependencies: // - target: StaticLibrary // - target: ResourceBundle // # Won't embed FrameworkC.framework, so should embed in tests // - framework: FrameworkC.framework // - carthage: CarthageA // - carthage: CarthageB // embed: false // - package: RxSwift // product: RxSwift // - package: RxSwift // product: RxCocoa // - package: RxSwift // product: RxRelay // iOSFrameworkB // dependencies: // - target: iOSFrameworkA // # Won't embed FrameworkD.framework, so should embed in tests // - framework: FrameworkD.framework // - framework: FrameworkE.framework // embed: true // - framework: FrameworkF.framework // embed: false // - carthage: CarthageC // embed: true // AppTest // dependencies: // # Being an app, shouldn't be embedded // - target: App // - target: iOSFrameworkB // - carthage: CarthageD // # should be implicitly added // # - target: iOSFrameworkA // # embed: true // # - target: StaticLibrary // # embed: false // # - framework: FrameworkZ.framework // # - target: iOSFrameworkZ // # embed: true // # - carthage: CarthageZ // # embed: false // # - carthage: CarthageA // # embed: true // # - framework: FrameworkC.framework // # embed: true // # - framework: FrameworkD.framework // # embed: true // // AppTestWithoutTransitive // dependencies: // # Being an app, shouldn't be embedded // - target: App // - target: iOSFrameworkB // - carthage: CarthageD // // packages: // RxSwift: // url: https://github.com/ReactiveX/RxSwift // majorVersion: 5.1.0 var expectedResourceFiles: [String: Set<String>] = [:] var expectedBundlesFiles: [String: Set<String>] = [:] var expectedLinkedFiles: [String: Set<String>] = [:] var expectedEmbeddedFrameworks: [String: Set<String>] = [:] let app = Target( name: "App", type: .application, platform: .iOS, // Embeds it's frameworks, so they shouldn't embed in AppTest dependencies: [ Dependency(type: .framework, reference: "FrameworkA.framework"), Dependency(type: .framework, reference: "FrameworkB.framework", embed: false), ] ) expectedResourceFiles[app.name] = Set() expectedLinkedFiles[app.name] = Set([ "FrameworkA.framework", "FrameworkB.framework", ]) expectedEmbeddedFrameworks[app.name] = Set([ "FrameworkA.framework", ]) let iosFrameworkZ = Target( name: "iOSFrameworkZ", type: .framework, platform: .iOS, dependencies: [] ) expectedResourceFiles[iosFrameworkZ.name] = Set() expectedLinkedFiles[iosFrameworkZ.name] = Set() expectedEmbeddedFrameworks[iosFrameworkZ.name] = Set() let iosFrameworkX = Target( name: "iOSFrameworkX", type: .framework, platform: .iOS, dependencies: [] ) expectedResourceFiles[iosFrameworkX.name] = Set() expectedLinkedFiles[iosFrameworkX.name] = Set() expectedEmbeddedFrameworks[iosFrameworkX.name] = Set() let staticLibrary = Target( name: "StaticLibrary", type: .staticLibrary, platform: .iOS, dependencies: [ Dependency(type: .target, reference: iosFrameworkZ.name, link: true), Dependency(type: .framework, reference: "FrameworkZ.framework", link: true), Dependency(type: .target, reference: iosFrameworkX.name /* , link: false */ ), Dependency(type: .framework, reference: "FrameworkX.framework" /* , link: false */ ), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageZ"), Dependency(type: .bundle, reference: "BundleA.bundle"), ] ) expectedResourceFiles[staticLibrary.name] = Set() expectedBundlesFiles[staticLibrary.name] = Set() expectedLinkedFiles[staticLibrary.name] = Set([ iosFrameworkZ.filename, "FrameworkZ.framework", ]) expectedEmbeddedFrameworks[staticLibrary.name] = Set() let resourceBundle = Target( name: "ResourceBundle", type: .bundle, platform: .iOS, dependencies: [] ) expectedResourceFiles[resourceBundle.name] = Set() expectedLinkedFiles[resourceBundle.name] = Set() expectedEmbeddedFrameworks[resourceBundle.name] = Set() let iosFrameworkA = Target( name: "iOSFrameworkA", type: .framework, platform: .iOS, dependencies: [ Dependency(type: .target, reference: resourceBundle.name), Dependency(type: .framework, reference: "FrameworkC.framework"), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageA"), Dependency(type: .package(product: "RxSwift"), reference: "RxSwift"), Dependency(type: .package(product: "RxCocoa"), reference: "RxSwift"), Dependency(type: .package(product: "RxRelay"), reference: "RxSwift"), // Validate - Do not link package Dependency(type: .package(product: "KeychainAccess"), reference: "KeychainAccess", link: false), // Statically linked, so don't embed into test Dependency(type: .target, reference: staticLibrary.name), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageB", embed: false), Dependency(type: .bundle, reference: "BundleA.bundle"), ] ) expectedResourceFiles[iosFrameworkA.name] = Set() expectedBundlesFiles[iosFrameworkA.name] = Set([ "BundleA.bundle", ]) expectedLinkedFiles[iosFrameworkA.name] = Set([ "FrameworkC.framework", iosFrameworkZ.filename, iosFrameworkX.filename, "FrameworkZ.framework", "FrameworkX.framework", "CarthageZ.framework", "CarthageA.framework", "CarthageB.framework", "RxSwift", "RxCocoa", "RxRelay", ]) expectedEmbeddedFrameworks[iosFrameworkA.name] = Set() let iosFrameworkB = Target( name: "iOSFrameworkB", type: .framework, platform: .iOS, dependencies: [ Dependency(type: .target, reference: iosFrameworkA.name), Dependency(type: .framework, reference: "FrameworkD.framework"), // Embedded into framework, so don't embed into test Dependency(type: .framework, reference: "FrameworkE.framework", embed: true), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageC", embed: true), // Statically linked, so don't embed into test Dependency(type: .framework, reference: "FrameworkF.framework", embed: false), ] ) expectedResourceFiles[iosFrameworkB.name] = Set() expectedLinkedFiles[iosFrameworkB.name] = Set([ iosFrameworkA.filename, iosFrameworkZ.filename, iosFrameworkX.filename, "FrameworkZ.framework", "FrameworkX.framework", "CarthageZ.framework", "FrameworkC.framework", "FrameworkD.framework", "FrameworkE.framework", "FrameworkF.framework", "CarthageA.framework", "CarthageB.framework", "CarthageC.framework", "RxSwift", "RxCocoa", "RxRelay", ]) expectedEmbeddedFrameworks[iosFrameworkB.name] = Set([ "FrameworkE.framework", "CarthageC.framework", ]) let appTest = Target( name: "AppTest", type: .unitTestBundle, platform: .iOS, dependencies: [ Dependency(type: .target, reference: app.name), Dependency(type: .target, reference: iosFrameworkB.name), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "CarthageD"), ], directlyEmbedCarthageDependencies: false ) expectedResourceFiles[appTest.name] = Set([ resourceBundle.filename, ]) expectedLinkedFiles[appTest.name] = Set([ iosFrameworkA.filename, staticLibrary.filename, iosFrameworkZ.filename, iosFrameworkX.filename, "FrameworkZ.framework", "FrameworkX.framework", "CarthageZ.framework", "FrameworkF.framework", "FrameworkC.framework", iosFrameworkB.filename, "FrameworkD.framework", "CarthageA.framework", "CarthageB.framework", "CarthageD.framework", "RxSwift", "RxCocoa", "RxRelay", ]) expectedEmbeddedFrameworks[appTest.name] = Set([ iosFrameworkA.filename, iosFrameworkZ.filename, iosFrameworkX.filename, "FrameworkZ.framework", "FrameworkX.framework", "FrameworkC.framework", iosFrameworkB.filename, "FrameworkD.framework", ]) var appTestWithoutTransitive = appTest appTestWithoutTransitive.name = "AppTestWithoutTransitive" appTestWithoutTransitive.transitivelyLinkDependencies = false expectedResourceFiles[appTestWithoutTransitive.name] = Set([]) expectedLinkedFiles[appTestWithoutTransitive.name] = Set([ iosFrameworkB.filename, "CarthageD.framework", ]) expectedEmbeddedFrameworks[appTestWithoutTransitive.name] = Set([ iosFrameworkB.filename, ]) let XCTestPath = "Platforms/iPhoneOS.platform/Developer/Library/Frameworks/XCTest.framework" let GXToolsPath = "Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/GXTools.framework" let XCTAutomationPath = "Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/XCTAutomationSupport.framework" let stickerPack = Target( name: "MyStickerApp", type: .stickerPack, platform: .iOS, dependencies: [ Dependency(type: .sdk(root: nil), reference: "NotificationCenter.framework"), Dependency(type: .sdk(root: "DEVELOPER_DIR"), reference: XCTestPath), Dependency(type: .sdk(root: "DEVELOPER_DIR"), reference: GXToolsPath, embed: true), Dependency(type: .sdk(root: "DEVELOPER_DIR"), reference: XCTAutomationPath, embed: true, codeSign: true), ] ) expectedResourceFiles[stickerPack.name] = nil expectedLinkedFiles[stickerPack.name] = Set([ "XCTest.framework", "NotificationCenter.framework", "GXTools.framework", "XCTAutomationSupport.framework" ]) expectedEmbeddedFrameworks[stickerPack.name] = Set([ "GXTools.framework", "XCTAutomationSupport.framework" ]) let targets = [app, iosFrameworkZ, iosFrameworkX, staticLibrary, resourceBundle, iosFrameworkA, iosFrameworkB, appTest, appTestWithoutTransitive, stickerPack] let packages: [String: SwiftPackage] = [ "RxSwift": .remote(url: "https://github.com/ReactiveX/RxSwift", versionRequirement: .upToNextMajorVersion("5.1.1")), "KeychainAccess": .remote(url: "https://github.com/kishikawakatsumi/KeychainAccess", versionRequirement: .upToNextMajorVersion("4.2.0")) ] let project = Project( name: "test", targets: targets, packages: packages, options: SpecOptions(transitivelyLinkDependencies: true) ) let pbxProject = try project.generatePbxProj() for target in targets { let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == target.name })) let buildPhases = nativeTarget.buildPhases let resourcesPhases = pbxProject.resourcesBuildPhases.filter { buildPhases.contains($0) } let frameworkPhases = pbxProject.frameworksBuildPhases.filter { buildPhases.contains($0) } let copyFilesPhases = pbxProject.copyFilesBuildPhases.filter { buildPhases.contains($0) } let embedFrameworkPhase = copyFilesPhases.first { $0.dstSubfolderSpec == .frameworks } let copyBundlesPhase = copyFilesPhases.first { $0.dstSubfolderSpec == .resources } // All targets should have a compile sources phase, // except for the resourceBundle and sticker pack one let targetsGeneratingSourcePhases = targets .filter { ![.bundle, .stickerPack].contains($0.type) } let sourcesPhases = pbxProject.sourcesBuildPhases try expect(sourcesPhases.count) == targetsGeneratingSourcePhases.count // ensure only the right resources are copied, no more, no less if let expectedResourceFiles = expectedResourceFiles[target.name] { try expect(resourcesPhases.count) == (expectedResourceFiles.isEmpty ? 0 : 1) if !expectedResourceFiles.isEmpty { let resourceFiles = (resourcesPhases[0].files ?? []) .compactMap { $0.file } .map { $0.nameOrPath } try expect(Set(resourceFiles)) == expectedResourceFiles } } else { try expect(resourcesPhases.count) == 0 } // ensure only the right things are linked, no more, no less let expectedLinkedFiles = expectedLinkedFiles[target.name]! try expect(frameworkPhases.count) == (expectedLinkedFiles.isEmpty ? 0 : 1) if !expectedLinkedFiles.isEmpty { let linkFrameworks = (frameworkPhases[0].files ?? []) .compactMap { $0.file?.nameOrPath } let linkPackages = (frameworkPhases[0].files ?? []) .compactMap { $0.product?.productName } try expect(Array(Set(linkFrameworks + linkPackages)).sorted()) == Array(expectedLinkedFiles).sorted() } var expectedCopyFilesPhasesCount = 0 // ensure only the right things are embedded, no more, no less if let expectedEmbeddedFrameworks = expectedEmbeddedFrameworks[target.name], !expectedEmbeddedFrameworks.isEmpty { expectedCopyFilesPhasesCount += 1 let copyFiles = (embedFrameworkPhase?.files ?? []) .compactMap { $0.file?.nameOrPath } try expect(Set(copyFiles)) == expectedEmbeddedFrameworks } if let expectedBundlesFiles = expectedBundlesFiles[target.name], target.type != .staticLibrary && target.type != .dynamicLibrary { expectedCopyFilesPhasesCount += 1 let copyBundles = (copyBundlesPhase?.files ?? []) .compactMap { $0.file?.nameOrPath } try expect(Set(copyBundles)) == expectedBundlesFiles } try expect(copyFilesPhases.count) == expectedCopyFilesPhasesCount } } $0.it("ensures static frameworks are not embedded by default") { let app = Target( name: "App", type: .application, platform: .iOS, dependencies: [ Dependency(type: .target, reference: "DynamicFramework"), Dependency(type: .target, reference: "DynamicFrameworkNotEmbedded", embed: false), Dependency(type: .target, reference: "StaticFramework"), Dependency(type: .target, reference: "StaticFrameworkExplicitlyEmbedded", embed: true), Dependency(type: .target, reference: "StaticFramework2"), Dependency(type: .target, reference: "StaticFramework2ExplicitlyEmbedded", embed: true), Dependency(type: .target, reference: "StaticLibrary"), ] ) let targets = [ app, Target( name: "DynamicFramework", type: .framework, platform: .iOS ), Target( name: "DynamicFrameworkNotEmbedded", type: .framework, platform: .iOS ), Target( name: "StaticFramework", type: .framework, platform: .iOS, settings: Settings(buildSettings: ["MACH_O_TYPE": "staticlib"]) ), Target( name: "StaticFrameworkExplicitlyEmbedded", type: .framework, platform: .iOS, settings: Settings(buildSettings: ["MACH_O_TYPE": "staticlib"]) ), Target( name: "StaticFramework2", type: .staticFramework, platform: .iOS ), Target( name: "StaticFramework2ExplicitlyEmbedded", type: .staticFramework, platform: .iOS ), Target( name: "StaticLibrary", type: .staticLibrary, platform: .iOS ), ] let expectedLinkedFiles = Set([ "DynamicFramework.framework", "DynamicFrameworkNotEmbedded.framework", "StaticFramework.framework", "StaticFrameworkExplicitlyEmbedded.framework", "StaticFramework2.framework", "StaticFramework2ExplicitlyEmbedded.framework", "libStaticLibrary.a", ]) let expectedEmbeddedFrameworks = Set([ "DynamicFramework.framework", "StaticFrameworkExplicitlyEmbedded.framework", "StaticFramework2ExplicitlyEmbedded.framework" ]) let project = Project( name: "test", targets: targets ) let pbxProject = try project.generatePbxProj() let appTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let buildPhases = appTarget.buildPhases let frameworkPhases = pbxProject.frameworksBuildPhases.filter { buildPhases.contains($0) } let copyFilesPhases = pbxProject.copyFilesBuildPhases.filter { buildPhases.contains($0) } let embedFrameworkPhase = copyFilesPhases.first { $0.dstSubfolderSpec == .frameworks } // Ensure all targets are linked let linkFrameworks = (frameworkPhases[0].files ?? []).compactMap { $0.file?.nameOrPath } let linkPackages = (frameworkPhases[0].files ?? []).compactMap { $0.product?.productName } try expect(Set(linkFrameworks + linkPackages)) == expectedLinkedFiles // Ensure only dynamic frameworks are embedded (unless there's an explicit override) let embeddedFrameworks = Set((embedFrameworkPhase?.files ?? []).compactMap { $0.file?.nameOrPath }) try expect(embeddedFrameworks) == expectedEmbeddedFrameworks } $0.it("copies files only on install in the Embed Frameworks step") { let app = Target( name: "App", type: .application, platform: .iOS, // Embeds it's frameworks, so they shouldn't embed in AppTest dependencies: [ Dependency(type: .framework, reference: "FrameworkA.framework"), Dependency(type: .framework, reference: "FrameworkB.framework", embed: false), ], onlyCopyFilesOnInstall: true ) let project = Project(name: "test",targets: [app]) let pbxProject = try project.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let buildPhases = nativeTarget.buildPhases let embedFrameworksPhase = pbxProject .copyFilesBuildPhases .filter { buildPhases.contains($0) } .first { $0.dstSubfolderSpec == .frameworks } let phase = try unwrap(embedFrameworksPhase) try expect(phase.buildActionMask) == PBXProjGenerator.copyFilesActionMask try expect(phase.runOnlyForDeploymentPostprocessing) == true } $0.it("copies files only on install in the Embed App Extensions step") { let appExtension = Target( name: "AppExtension", type: .appExtension, platform: .tvOS ) let app = Target( name: "App", type: .application, platform: .tvOS, dependencies: [ Dependency(type: .target, reference: "AppExtension") ], onlyCopyFilesOnInstall: true ) let project = Project(name: "test", targets: [app, appExtension]) let pbxProject = try project.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let buildPhases = nativeTarget.buildPhases let embedAppExtensionsPhase = pbxProject .copyFilesBuildPhases .filter { buildPhases.contains($0) } .first { $0.dstSubfolderSpec == .plugins } let phase = try unwrap(embedAppExtensionsPhase) try expect(phase.buildActionMask) == PBXProjGenerator.copyFilesActionMask try expect(phase.runOnlyForDeploymentPostprocessing) == true } $0.it("copies files only on install in the Embed Frameworks and Embed App Extensions steps") { let appExtension = Target( name: "AppExtension", type: .appExtension, platform: .tvOS ) let app = Target( name: "App", type: .application, platform: .tvOS, dependencies: [ Dependency(type: .target, reference: "AppExtension"), Dependency(type: .framework, reference: "FrameworkA.framework"), Dependency(type: .framework, reference: "FrameworkB.framework", embed: false), ], onlyCopyFilesOnInstall: true ) let project = Project(name: "test", targets: [app, appExtension]) let pbxProject = try project.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let buildPhases = nativeTarget.buildPhases let embedFrameworksPhase = pbxProject .copyFilesBuildPhases .filter { buildPhases.contains($0) } .first { $0.dstSubfolderSpec == .frameworks } let embedFrameworksPhaseValue = try unwrap(embedFrameworksPhase) try expect(embedFrameworksPhaseValue.buildActionMask) == PBXProjGenerator.copyFilesActionMask try expect(embedFrameworksPhaseValue.runOnlyForDeploymentPostprocessing) == true let embedAppExtensionsPhase = pbxProject .copyFilesBuildPhases .filter { buildPhases.contains($0) } .first { $0.dstSubfolderSpec == .plugins } let embedAppExtensionsPhaseValue = try unwrap(embedAppExtensionsPhase) try expect(embedAppExtensionsPhaseValue.buildActionMask) == PBXProjGenerator.copyFilesActionMask try expect(embedAppExtensionsPhaseValue.runOnlyForDeploymentPostprocessing) == true } $0.it("sets -ObjC for targets that depend on requiresObjCLinking targets") { let requiresObjCLinking = Target( name: "requiresObjCLinking", type: .staticLibrary, platform: .iOS, dependencies: [], requiresObjCLinking: true ) let doesntRequireObjCLinking = Target( name: "doesntRequireObjCLinking", type: .staticLibrary, platform: .iOS, dependencies: [], requiresObjCLinking: false ) let implicitlyRequiresObjCLinking = Target( name: "implicitlyRequiresObjCLinking", type: .staticLibrary, platform: .iOS, sources: [TargetSource(path: "StaticLibrary_ObjC/StaticLibrary_ObjC.m")], dependencies: [] ) let framework = Target( name: "framework", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: requiresObjCLinking.name, link: false)] ) let app1 = Target( name: "app1", type: .application, platform: .iOS, dependencies: [Dependency(type: .target, reference: requiresObjCLinking.name)] ) let app2 = Target( name: "app2", type: .application, platform: .iOS, dependencies: [Dependency(type: .target, reference: doesntRequireObjCLinking.name)] ) let app3 = Target( name: "app3", type: .application, platform: .iOS, dependencies: [Dependency(type: .target, reference: implicitlyRequiresObjCLinking.name)] ) let targets = [requiresObjCLinking, doesntRequireObjCLinking, implicitlyRequiresObjCLinking, framework, app1, app2, app3] let project = Project( basePath: fixturePath + "TestProject", name: "test", targets: targets, options: SpecOptions() ) let pbxProj = try project.generatePbxProj() func buildSettings(for target: Target) throws -> BuildSettings { guard let nativeTarget = pbxProj.targets(named: target.name).first, let buildConfigList = nativeTarget.buildConfigurationList, let buildConfig = buildConfigList.buildConfigurations.first else { throw failure("XCBuildConfiguration not found for Target \(target.name.quoted)") } return buildConfig.buildSettings } let frameworkOtherLinkerSettings = try buildSettings(for: framework)["OTHER_LDFLAGS"] as? [String] ?? [] let app1OtherLinkerSettings = try buildSettings(for: app1)["OTHER_LDFLAGS"] as? [String] ?? [] let app2OtherLinkerSettings = try buildSettings(for: app2)["OTHER_LDFLAGS"] as? [String] ?? [] let app3OtherLinkerSettings = try buildSettings(for: app3)["OTHER_LDFLAGS"] as? [String] ?? [] try expect(frameworkOtherLinkerSettings.contains("-ObjC")) == false try expect(app1OtherLinkerSettings.contains("-ObjC")) == true try expect(app2OtherLinkerSettings.contains("-ObjC")) == false try expect(app3OtherLinkerSettings.contains("-ObjC")) == true } $0.it("copies Swift Objective-C Interface Header") { let swiftStaticLibraryWithHeader = Target( name: "swiftStaticLibraryWithHeader", type: .staticLibrary, platform: .iOS, sources: [TargetSource(path: "StaticLibrary_Swift/StaticLibrary.swift")], dependencies: [] ) let swiftStaticLibraryWithoutHeader1 = Target( name: "swiftStaticLibraryWithoutHeader1", type: .staticLibrary, platform: .iOS, settings: Settings(buildSettings: ["SWIFT_OBJC_INTERFACE_HEADER_NAME": ""]), sources: [TargetSource(path: "StaticLibrary_Swift/StaticLibrary.swift")], dependencies: [] ) let swiftStaticLibraryWithoutHeader2 = Target( name: "swiftStaticLibraryWithoutHeader2", type: .staticLibrary, platform: .iOS, settings: Settings(buildSettings: ["SWIFT_INSTALL_OBJC_HEADER": false]), sources: [TargetSource(path: "StaticLibrary_Swift/StaticLibrary.swift")], dependencies: [] ) let swiftStaticLibraryWithoutHeader3 = Target( name: "swiftStaticLibraryWithoutHeader3", type: .staticLibrary, platform: .iOS, settings: Settings(buildSettings: ["SWIFT_INSTALL_OBJC_HEADER": "NO"]), sources: [TargetSource(path: "StaticLibrary_Swift/StaticLibrary.swift")], dependencies: [] ) let objCStaticLibrary = Target( name: "objCStaticLibrary", type: .staticLibrary, platform: .iOS, sources: [TargetSource(path: "StaticLibrary_ObjC/StaticLibrary_ObjC.m")], dependencies: [] ) let targets = [swiftStaticLibraryWithHeader, swiftStaticLibraryWithoutHeader1, swiftStaticLibraryWithoutHeader2, swiftStaticLibraryWithoutHeader3, objCStaticLibrary] let project = Project( basePath: fixturePath + "TestProject", name: "test", targets: targets, options: SpecOptions() ) let pbxProject = try project.generatePbxProj() func scriptBuildPhases(target: Target) throws -> [PBXShellScriptBuildPhase] { let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == target.name })) let buildPhases = nativeTarget.buildPhases let scriptPhases = buildPhases.compactMap { $0 as? PBXShellScriptBuildPhase } return scriptPhases } let expectedScriptPhase = PBXShellScriptBuildPhase( name: "Copy Swift Objective-C Interface Header", inputPaths: ["$(DERIVED_SOURCES_DIR)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"], outputPaths: ["$(BUILT_PRODUCTS_DIR)/include/$(PRODUCT_MODULE_NAME)/$(SWIFT_OBJC_INTERFACE_HEADER_NAME)"], shellPath: "/bin/sh", shellScript: "ditto \"${SCRIPT_INPUT_FILE_0}\" \"${SCRIPT_OUTPUT_FILE_0}\"\n" ) try expect(scriptBuildPhases(target: swiftStaticLibraryWithHeader)) == [expectedScriptPhase] try expect(scriptBuildPhases(target: swiftStaticLibraryWithoutHeader1)) == [] try expect(scriptBuildPhases(target: swiftStaticLibraryWithoutHeader2)) == [] try expect(scriptBuildPhases(target: swiftStaticLibraryWithoutHeader3)) == [] try expect(scriptBuildPhases(target: objCStaticLibrary)) == [] } $0.it("generates run scripts") { var scriptSpec = project scriptSpec.targets[0].preBuildScripts = [BuildScript(script: .script("script1"))] scriptSpec.targets[0].postCompileScripts = [BuildScript(script: .script("script2"))] scriptSpec.targets[0].postBuildScripts = [ BuildScript(script: .script("script3")), BuildScript(script: .script("script4"), discoveredDependencyFile: "$(DERIVED_FILE_DIR)/target.d") ] let pbxProject = try scriptSpec.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.buildPhases.count >= 4 })) let buildPhases = nativeTarget.buildPhases let scripts = pbxProject.shellScriptBuildPhases try expect(scripts.count) == 4 let script1 = scripts.first { $0.shellScript == "script1" }! let script2 = scripts.first { $0.shellScript == "script2" }! let script3 = scripts.first { $0.shellScript == "script3" }! let script4 = scripts.first { $0.shellScript == "script4" }! try expect(buildPhases.contains(script1)) == true try expect(buildPhases.contains(script2)) == true try expect(buildPhases.contains(script3)) == true try expect(buildPhases.contains(script4)) == true try expect(script1.dependencyFile).beNil() try expect(script2.dependencyFile).beNil() try expect(script3.dependencyFile).beNil() try expect(script4.dependencyFile) == "$(DERIVED_FILE_DIR)/target.d" } $0.it("generates targets with cylical dependencies") { let target1 = Target( name: "target1", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: "target2")] ) let target2 = Target( name: "target2", type: .framework, platform: .iOS, dependencies: [Dependency(type: .target, reference: "target1")] ) let project = Project( name: "test", targets: [target1, target2] ) _ = try project.generatePbxProj() } $0.it("generates build rules") { var scriptSpec = project scriptSpec.targets[0].buildRules = [ BuildRule( fileType: .type("sourcecode.swift"), action: .script("do thing"), name: "My Rule", outputFiles: ["file1.swift", "file2.swift"], outputFilesCompilerFlags: ["--zee", "--bee"] ), BuildRule( fileType: .pattern("*.plist"), action: .compilerSpec("com.apple.build-tasks.copy-plist-file") ), ] let pbxProject = try scriptSpec.generatePbxProj() let buildRules = pbxProject.buildRules try expect(buildRules.count) == 2 let first = buildRules.first { $0.name == "My Rule" }! let second = buildRules.first { $0.name != "My Rule" }! try expect(first.name) == "My Rule" try expect(first.isEditable) == true try expect(first.outputFiles) == ["file1.swift", "file2.swift"] try expect(first.outputFilesCompilerFlags) == ["--zee", "--bee"] try expect(first.script) == "do thing" try expect(first.fileType) == "sourcecode.swift" try expect(first.compilerSpec) == "com.apple.compilers.proxy.script" try expect(first.filePatterns).beNil() try expect(second.name) == "Build Rule" try expect(second.fileType) == "pattern.proxy" try expect(second.filePatterns) == "*.plist" try expect(second.compilerSpec) == "com.apple.build-tasks.copy-plist-file" try expect(second.script).beNil() try expect(second.outputFiles) == [] try expect(second.outputFilesCompilerFlags) == [] } $0.it("generates dependency build file settings") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .target, reference: "MyFramework"), Dependency(type: .target, reference: "MyOptionalFramework", weakLink: true), ] ) let project = Project(name: "test", targets: [app, framework, optionalFramework, uiTest]) let pbxProject = try project.generatePbxProj() let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let frameworkPhases = nativeTarget.buildPhases.compactMap { $0 as? PBXFrameworksBuildPhase } let frameworkBuildFiles = frameworkPhases[0].files ?? [] let buildFileSettings = frameworkBuildFiles.map { $0.settings } try expect(frameworkBuildFiles.count) == 2 try expect(buildFileSettings.compactMap { $0 }.count) == 1 try expect(buildFileSettings.compactMap { $0?["ATTRIBUTES"] }.count) == 1 try expect(buildFileSettings.compactMap { $0?["ATTRIBUTES"] as? [String] }.first) == ["Weak"] } $0.it("generates swift packages") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .package(product: "ProjectSpec"), reference: "XcodeGen"), Dependency(type: .package(product: nil), reference: "Codability"), ] ) let project = Project(name: "test", targets: [app], packages: [ "XcodeGen": .remote(url: "http://github.com/yonaskolb/XcodeGen", versionRequirement: .branch("master")), "Codability": .remote(url: "http://github.com/yonaskolb/Codability", versionRequirement: .exact("1.0.0")), "Yams": .local(path: "../Yams", group: nil), ], options: .init(localPackagesGroup: "MyPackages")) let pbxProject = try project.generatePbxProj(specValidate: false) let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let projectSpecDependency = try unwrap(nativeTarget.packageProductDependencies.first(where: { $0.productName == "ProjectSpec" })) try expect(projectSpecDependency.package?.name) == "XcodeGen" try expect(projectSpecDependency.package?.versionRequirement) == .branch("master") let codabilityDependency = try unwrap(nativeTarget.packageProductDependencies.first(where: { $0.productName == "Codability" })) try expect(codabilityDependency.package?.name) == "Codability" try expect(codabilityDependency.package?.versionRequirement) == .exact("1.0.0") let localPackagesGroup = try unwrap(try pbxProject.getMainGroup().children.first(where: { $0.name == "MyPackages" }) as? PBXGroup) let yamsLocalPackageFile = try unwrap(pbxProject.fileReferences.first(where: { $0.path == "../Yams" })) try expect(localPackagesGroup.children.contains(yamsLocalPackageFile)) == true try expect(yamsLocalPackageFile.lastKnownFileType) == "folder" } $0.it("generates local swift packages") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .package(product: nil), reference: "XcodeGen"), ] ) let project = Project(name: "test", targets: [app], packages: ["XcodeGen": .local(path: "../XcodeGen", group: nil)]) let pbxProject = try project.generatePbxProj(specValidate: false) let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let localPackageFile = try unwrap(pbxProject.fileReferences.first(where: { $0.path == "../XcodeGen" })) try expect(localPackageFile.lastKnownFileType) == "folder" let frameworkPhases = nativeTarget.buildPhases.compactMap { $0 as? PBXFrameworksBuildPhase } guard let frameworkPhase = frameworkPhases.first else { return XCTFail("frameworkPhases should have more than one") } guard let file = frameworkPhase.files?.first else { return XCTFail("frameworkPhase should have file") } try expect(file.product?.productName) == "XcodeGen" } $0.it("generates local swift packages with custom xcode path") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .package(product: nil), reference: "XcodeGen"), ] ) let project = Project(name: "test", targets: [app], packages: ["XcodeGen": .local(path: "../XcodeGen", group: "Packages/Feature")]) let pbxProject = try project.generatePbxProj(specValidate: false) let nativeTarget = try unwrap(pbxProject.nativeTargets.first(where: { $0.name == app.name })) let localPackageFile = try unwrap(pbxProject.fileReferences.first(where: { $0.path == "../XcodeGen" })) try expect(localPackageFile.lastKnownFileType) == "folder" let frameworkPhases = nativeTarget.buildPhases.compactMap { $0 as? PBXFrameworksBuildPhase } guard let frameworkPhase = frameworkPhases.first else { return XCTFail("frameworkPhases should have more than one") } guard let file = frameworkPhase.files?.first else { return XCTFail("frameworkPhase should have file") } try expect(file.product?.productName) == "XcodeGen" } $0.it("generates info.plist") { let plist = Plist(path: "Info.plist", attributes: ["UISupportedInterfaceOrientations": ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationLandscapeLeft"]]) let tempPath = Path.temporary + "info" let project = Project(basePath: tempPath, name: "", targets: [Target(name: "", type: .application, platform: .iOS, info: plist)]) let pbxProject = try project.generatePbxProj() let writer = FileWriter(project: project) try writer.writePlists() let targetConfig = try unwrap(pbxProject.nativeTargets.first?.buildConfigurationList?.buildConfigurations.first) try expect(targetConfig.buildSettings["INFOPLIST_FILE"] as? String) == plist.path let infoPlistFile = tempPath + plist.path let data: Data = try infoPlistFile.read() let infoPlist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String: Any] let expectedInfoPlist: [String: Any] = [ "CFBundleIdentifier": "$(PRODUCT_BUNDLE_IDENTIFIER)", "CFBundleInfoDictionaryVersion": "6.0", "CFBundleName": "$(PRODUCT_NAME)", "CFBundleExecutable": "$(EXECUTABLE_NAME)", "CFBundleDevelopmentRegion": "$(DEVELOPMENT_LANGUAGE)", "CFBundleShortVersionString": "1.0", "CFBundleVersion": "1", "CFBundlePackageType": "APPL", "UISupportedInterfaceOrientations": ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationLandscapeLeft"], ] try expect(NSDictionary(dictionary: expectedInfoPlist).isEqual(to: infoPlist)).beTrue() } $0.it("info doesn't override info.plist setting") { let predefinedPlistPath = "Predefined.plist" // generate plist let plist = Plist(path: "Info.plist", attributes: ["UISupportedInterfaceOrientations": ["UIInterfaceOrientationPortrait", "UIInterfaceOrientationLandscapeLeft"]]) let tempPath = Path.temporary + "info" // create project with a predefined plist let project = Project(basePath: tempPath, name: "", targets: [Target(name: "", type: .application, platform: .iOS, settings: Settings(buildSettings: ["INFOPLIST_FILE": predefinedPlistPath]), info: plist)]) let pbxProject = try project.generatePbxProj() let writer = FileWriter(project: project) try writer.writePlists() let targetConfig = try unwrap(pbxProject.nativeTargets.first?.buildConfigurationList?.buildConfigurations.first) // generated plist should not be in buildsettings try expect(targetConfig.buildSettings["INFOPLIST_FILE"] as? String) == predefinedPlistPath } describe("Carthage dependencies") { $0.context("with static dependency") { $0.it("should set dependencies") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .carthage(findFrameworks: true, linkType: .static), reference: "MyStaticFramework"), ] ) let project = Project(name: "test", targets: [app]) let pbxProject = try project.generatePbxProj() let target = pbxProject.nativeTargets.first! let configuration = target.buildConfigurationList!.buildConfigurations.first! try expect(configuration.buildSettings["FRAMEWORK_SEARCH_PATHS"] as? [String]) == ["$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS/Static"] let frameworkBuildPhase = try target.frameworksBuildPhase() guard let files = frameworkBuildPhase?.files, let file = files.first else { return XCTFail("frameworkBuildPhase should have files") } try expect(files.count) == 1 try expect(file.file?.nameOrPath) == "MyStaticFramework.framework" try expect(target.carthageCopyFrameworkBuildPhase).beNil() } } $0.context("with mixed dependencies") { $0.it("should set dependencies") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .carthage(findFrameworks: true, linkType: .dynamic), reference: "MyDynamicFramework"), Dependency(type: .carthage(findFrameworks: true, linkType: .static), reference: "MyStaticFramework"), ] ) let project = Project(name: "test", targets: [app]) let pbxProject = try project.generatePbxProj() let target = pbxProject.nativeTargets.first! let configuration = target.buildConfigurationList!.buildConfigurations.first! try expect(configuration.buildSettings["FRAMEWORK_SEARCH_PATHS"] as? [String]) == ["$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", "$(PROJECT_DIR)/Carthage/Build/iOS/Static"] let frameworkBuildPhase = try target.frameworksBuildPhase() guard let files = frameworkBuildPhase?.files else { return XCTFail("frameworkBuildPhase should have files") } try expect(files.count) == 2 guard let dynamicFramework = files.first(where: { $0.file?.nameOrPath == "MyDynamicFramework.framework" }) else { return XCTFail("Framework Build Phase should have Dynamic Framework") } guard let _ = files.first(where: { $0.file?.nameOrPath == "MyStaticFramework.framework" }) else { return XCTFail("Framework Build Phase should have Static Framework") } guard let copyCarthagePhase = target.carthageCopyFrameworkBuildPhase else { return XCTFail("Carthage Build Phase should be exist") } try expect(copyCarthagePhase.inputPaths) == [dynamicFramework.file?.fullPath(sourceRoot: Path("$(SRCROOT)"))?.string] try expect(copyCarthagePhase.outputPaths) == ["$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/\(dynamicFramework.file!.path!)"] } } } $0.it("generate info.plist doesn't generate CFBundleExecutable for targets with type bundle") { let plist = Plist(path: "Info.plist", attributes: [:]) let tempPath = Path.temporary + "info" let project = Project(basePath: tempPath, name: "", targets: [Target(name: "", type: .bundle, platform: .iOS, info: plist)]) let pbxProject = try project.generatePbxProj() let writer = FileWriter(project: project) try writer.writePlists() let targetConfig = try unwrap(pbxProject.nativeTargets.first?.buildConfigurationList?.buildConfigurations.first) try expect(targetConfig.buildSettings["INFOPLIST_FILE"] as? String) == plist.path let infoPlistFile = tempPath + plist.path let data: Data = try infoPlistFile.read() let infoPlist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String: Any] let expectedInfoPlist: [String: Any] = [ "CFBundleIdentifier": "$(PRODUCT_BUNDLE_IDENTIFIER)", "CFBundleInfoDictionaryVersion": "6.0", "CFBundleName": "$(PRODUCT_NAME)", "CFBundleDevelopmentRegion": "$(DEVELOPMENT_LANGUAGE)", "CFBundleShortVersionString": "1.0", "CFBundleVersion": "1", "CFBundlePackageType": "BNDL", ] try expect(NSDictionary(dictionary: expectedInfoPlist).isEqual(to: infoPlist)).beTrue() } } } func testGenerateXcodeProjectWithDestination() throws { let groupName = "App_iOS" let sourceDirectory = fixturePath + "TestProject" + groupName let frameworkWithSources = Target( name: "MyFramework", type: .framework, platform: .iOS, sources: [TargetSource(path: sourceDirectory.string)] ) describe("generateXcodeProject") { $0.context("without projectDirectory") { $0.it("generate groups") { let project = Project(name: "test", targets: [frameworkWithSources]) let generator = ProjectGenerator(project: project) let generatedProject = try generator.generateXcodeProject() let group = generatedProject.pbxproj.groups.first(where: { $0.nameOrPath == groupName }) try expect(group?.path) == "App_iOS" } } $0.context("with projectDirectory") { $0.it("generate groups") { let destinationPath = fixturePath let project = Project(name: "test", targets: [frameworkWithSources]) let generator = ProjectGenerator(project: project) let generatedProject = try generator.generateXcodeProject(in: destinationPath) let group = generatedProject.pbxproj.groups.first(where: { $0.nameOrPath == groupName }) try expect(group?.path) == "TestProject/App_iOS" } $0.it("generate Info.plist") { let destinationPath = fixturePath let project = Project(name: "test", targets: [frameworkWithSources]) let generator = ProjectGenerator(project: project) let generatedProject = try generator.generateXcodeProject(in: destinationPath) let plists = generatedProject.pbxproj.buildConfigurations.compactMap { $0.buildSettings["INFOPLIST_FILE"] as? String } try expect(plists.count) == 2 for plist in plists { try expect(plist) == "TestProject/App_iOS/Info.plist" } } } describe("Carthage dependencies") { $0.context("with static dependency") { $0.it("should set dependencies") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .carthage(findFrameworks: true, linkType: .static), reference: "MyStaticFramework"), ] ) let project = Project(name: "test", targets: [app]) let pbxProject = try project.generatePbxProj() let target = pbxProject.nativeTargets.first! let configuration = target.buildConfigurationList!.buildConfigurations.first! try expect(configuration.buildSettings["FRAMEWORK_SEARCH_PATHS"] as? [String]) == ["$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS/Static"] let frameworkBuildPhase = try target.frameworksBuildPhase() guard let files = frameworkBuildPhase?.files, let file = files.first else { return XCTFail("frameworkBuildPhase should have files") } try expect(files.count) == 1 try expect(file.file?.nameOrPath) == "MyStaticFramework.framework" try expect(target.carthageCopyFrameworkBuildPhase).beNil() } } $0.context("with mixed dependencies") { $0.it("should set dependencies") { let app = Target( name: "MyApp", type: .application, platform: .iOS, dependencies: [ Dependency(type: .carthage(findFrameworks: true, linkType: .dynamic), reference: "MyDynamicFramework"), Dependency(type: .carthage(findFrameworks: true, linkType: .static), reference: "MyStaticFramework"), ] ) let project = Project(name: "test", targets: [app]) let pbxProject = try project.generatePbxProj() let target = pbxProject.nativeTargets.first! let configuration = target.buildConfigurationList!.buildConfigurations.first! try expect(configuration.buildSettings["FRAMEWORK_SEARCH_PATHS"] as? [String]) == ["$(inherited)", "$(PROJECT_DIR)/Carthage/Build/iOS", "$(PROJECT_DIR)/Carthage/Build/iOS/Static"] let frameworkBuildPhase = try target.frameworksBuildPhase() guard let files = frameworkBuildPhase?.files else { return XCTFail("frameworkBuildPhase should have files") } try expect(files.count) == 2 guard let dynamicFramework = files.first(where: { $0.file?.nameOrPath == "MyDynamicFramework.framework" }) else { return XCTFail("Framework Build Phase should have Dynamic Framework") } guard let _ = files.first(where: { $0.file?.nameOrPath == "MyStaticFramework.framework" }) else { return XCTFail("Framework Build Phase should have Static Framework") } guard let copyCarthagePhase = target.carthageCopyFrameworkBuildPhase else { return XCTFail("Carthage Build Phase should be exist") } try expect(copyCarthagePhase.inputPaths) == [dynamicFramework.file?.fullPath(sourceRoot: Path("$(SRCROOT)"))?.string] try expect(copyCarthagePhase.outputPaths) == ["$(BUILT_PRODUCTS_DIR)/$(FRAMEWORKS_FOLDER_PATH)/\(dynamicFramework.file!.path!)"] } } } } } func testGenerateXcodeProjectWithCustomDependencyDestinations() throws { describe("generateXcodeProject") { func generateProjectForApp(withDependencies: [Dependency], targets: [Target], packages: [String: SwiftPackage] = [:]) throws -> PBXProj { let app = Target( name: "App", type: .application, platform: .macOS, dependencies: withDependencies ) let project = Project( name: "test", targets: targets + [app], packages: packages ) return try project.generatePbxProj() } func expectCopyPhase(in project:PBXProj, withFilePaths: [String]? = nil, withProductPaths: [String]? = nil, toSubFolder subfolder: PBXCopyFilesBuildPhase.SubFolder, dstPath: String? = nil) throws { let phases = project.copyFilesBuildPhases try expect(phases.count) == 1 let phase = phases.first! try expect(phase.dstSubfolderSpec) == subfolder try expect(phase.dstPath) == dstPath if let paths = withFilePaths { try expect(phase.files?.count) == paths.count let filePaths = phase.files!.map { $0.file!.path } try expect(filePaths) == paths } if let paths = withProductPaths { try expect(phase.files?.count) == paths.count let filePaths = phase.files!.map { $0.product!.productName } try expect(filePaths) == paths } } $0.context("with target dependencies") { $0.context("application") { let appA = Target( name: "appA", type: .application, platform: .macOS ) let appB = Target( name: "appB", type: .application, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [ appA, appB ]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("framework") { let frameworkA = Target( name: "frameworkA", type: .framework, platform: .macOS ) let frameworkB = Target( name: "frameworkB", type: .framework, platform: .macOS ) $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true), Dependency(type: .target, reference: frameworkB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: frameworkB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("staticFramework") { let frameworkA = Target( name: "frameworkA", type: .staticFramework, platform: .macOS ) let frameworkB = Target( name: "frameworkB", type: .staticFramework, platform: .macOS ) $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true), Dependency(type: .target, reference: frameworkB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: frameworkB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("xcFramework") { let frameworkA = Target( name: "frameworkA", type: .xcFramework, platform: .macOS ) let frameworkB = Target( name: "frameworkB", type: .xcFramework, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true), Dependency(type: .target, reference: frameworkB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: frameworkA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: frameworkB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [frameworkA, frameworkB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.xcframework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("Dynamic Library") { let libraryA = Target( name: "libraryA", type: .dynamicLibrary, platform: .macOS ) let libraryB = Target( name: "libraryB", type: .dynamicLibrary, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true), Dependency(type: .target, reference: libraryB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: libraryB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["libraryA.dylib"], toSubFolder: .plugins, dstPath: "test") } } $0.context("Static Library") { let libraryA = Target( name: "libraryA", type: .staticLibrary, platform: .macOS ) let libraryB = Target( name: "libraryB", type: .staticLibrary, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true), Dependency(type: .target, reference: libraryB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them to custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: libraryB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["liblibraryA.a"], toSubFolder: .plugins, dstPath: "test") } } $0.context("bundle") { let bundleA = Target( name: "bundleA", type: .bundle, platform: .macOS ) let bundleB = Target( name: "bundleB", type: .bundle, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true), Dependency(type: .target, reference: bundleB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: bundleB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.bundle"], toSubFolder: .plugins, dstPath: "test") } } $0.context("unitTestBundle") { let bundleA = Target( name: "bundleA", type: .unitTestBundle, platform: .macOS ) let bundleB = Target( name: "bundleB", type: .unitTestBundle, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true), Dependency(type: .target, reference: bundleB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: bundleB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.xctest"], toSubFolder: .plugins, dstPath: "test") } } $0.context("uitTestBundle") { let bundleA = Target( name: "bundleA", type: .uiTestBundle, platform: .macOS ) let bundleB = Target( name: "bundleB", type: .uiTestBundle, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true), Dependency(type: .target, reference: bundleB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: bundleB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.xctest"], toSubFolder: .plugins, dstPath: "test") } } $0.context("appExtension") { let extA = Target( name: "extA", type: .appExtension, platform: .macOS ) let extB = Target( name: "extB", type: .appExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .executables, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .executables, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .executables, dstPath: "test") } } $0.context("extensionKit") { let extA = Target( name: "extA", type: .extensionKitExtension, platform: .macOS ) let extB = Target( name: "extB", type: .extensionKitExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .productsDirectory, dstPath: "$(EXTENSIONS_FOLDER_PATH)") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .productsDirectory, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .productsDirectory, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .productsDirectory, dstPath: "test") } } $0.context("commandLineTool") { let toolA = Target( name: "toolA", type: .commandLineTool, platform: .macOS ) let toolB = Target( name: "toolB", type: .commandLineTool, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: toolA.name, embed: true), Dependency(type: .target, reference: toolB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [toolA, toolB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: toolA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: toolB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [toolA, toolB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["toolA"], toSubFolder: .plugins, dstPath: "test") } } $0.context("watchApp") { let appA = Target( name: "appA", type: .watchApp, platform: .macOS ) let appB = Target( name: "appB", type: .watchApp, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("watch2App") { let appA = Target( name: "appA", type: .watch2App, platform: .macOS ) let appB = Target( name: "appB", type: .watch2App, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("watch2AppContainer") { let appA = Target( name: "appA", type: .watch2AppContainer, platform: .macOS ) let appB = Target( name: "appB", type: .watch2AppContainer, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("watchExtension") { let extA = Target( name: "extA", type: .watchExtension, platform: .macOS ) let extB = Target( name: "extB", type: .watchExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("watch2Extension") { let extA = Target( name: "extA", type: .watch2Extension, platform: .macOS ) let extB = Target( name: "extB", type: .watch2Extension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("tvExtension") { let extA = Target( name: "extA", type: .tvExtension, platform: .macOS ) let extB = Target( name: "extB", type: .tvExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("messagesApplication") { let appA = Target( name: "appA", type: .messagesApplication, platform: .macOS ) let appB = Target( name: "appB", type: .messagesApplication, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true), Dependency(type: .target, reference: appB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: appA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: appB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [appA, appB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["appA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("messagesExtension") { let extA = Target( name: "extA", type: .messagesExtension, platform: .macOS ) let extB = Target( name: "extB", type: .messagesExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("stickerPack") { let extA = Target( name: "extA", type: .stickerPack, platform: .macOS ) let extB = Target( name: "extB", type: .stickerPack, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("xpcService") { let xpcA = Target( name: "xpcA", type: .xpcService, platform: .macOS ) let xpcB = Target( name: "xpcB", type: .xpcService, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: xpcA.name, embed: true), Dependency(type: .target, reference: xpcB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [xpcA, xpcB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["xpcA.xpc"], toSubFolder: .productsDirectory, dstPath: "$(CONTENTS_FOLDER_PATH)/XPCServices") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: xpcA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: xpcB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [xpcA, xpcB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["xpcA.xpc"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("ocUnitTestBundle") { let bundleA = Target( name: "bundleA", type: .ocUnitTestBundle, platform: .macOS ) let bundleB = Target( name: "bundleB", type: .ocUnitTestBundle, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true), Dependency(type: .target, reference: bundleB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: bundleA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: bundleB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [bundleA, bundleB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.octest"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("xcodeExtension") { let extA = Target( name: "extA", type: .xcodeExtension, platform: .macOS ) let extB = Target( name: "extB", type: .xcodeExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("instrumentsPackage") { let pkgA = Target( name: "pkgA", type: .instrumentsPackage, platform: .macOS ) let pkgB = Target( name: "pkgB", type: .instrumentsPackage, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: pkgA.name, embed: true), Dependency(type: .target, reference: pkgB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [pkgA, pkgB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: pkgA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: pkgB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [pkgA, pkgB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["pkgA.instrpkg"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("intentsServiceExtension") { let extA = Target( name: "extA", type: .intentsServiceExtension, platform: .macOS ) let extB = Target( name: "extB", type: .intentsServiceExtension, platform: .macOS ) $0.it("embeds them into plugins without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true), Dependency(type: .target, reference: extB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .plugins, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: extA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: extB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .frameworks, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [extA, extB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["extA.appex"], toSubFolder: .frameworks, dstPath: "test") } } $0.context("appClip") { let clipA = Target( name: "clipA", type: .onDemandInstallCapableApplication, platform: .macOS ) let clipB = Target( name: "clipB", type: .onDemandInstallCapableApplication, platform: .macOS ) $0.it("does embed them into products directory without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: clipA.name, embed: true), Dependency(type: .target, reference: clipB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [clipA, clipB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["clipA.app"], toSubFolder: .productsDirectory, dstPath: "$(CONTENTS_FOLDER_PATH)/AppClips") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: clipA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: clipB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [clipA, clipB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["clipA.app"], toSubFolder: .plugins, dstPath: "test") } } $0.context("Metal Library") { let libraryA = Target( name: "libraryA", type: .metalLibrary, platform: .macOS ) let libraryB = Target( name: "libraryB", type: .metalLibrary, platform: .macOS ) $0.it("does not embed them without copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true), Dependency(type: .target, reference: libraryB.name, embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expect(pbxProject.copyFilesBuildPhases.count) == 0 } $0.it("embeds them to custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .target, reference: libraryA.name, embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .target, reference: libraryB.name, embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [libraryA, libraryB]) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["libraryA.metallib"], toSubFolder: .plugins, dstPath: "test") } } } $0.context("with framework dependencies") { $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .framework, reference: "frameworkA.framework", embed: true), Dependency(type: .framework, reference: "frameworkB.framework", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .framework, reference: "frameworkA.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .framework, reference: "frameworkB.framework", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .plugins, dstPath: "test") } $0.it("generates single copy phase for multiple frameworks with same copy phase spec") { // given let dependencies = [ Dependency(type: .framework, reference: "frameworkA.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .framework, reference: "frameworkB.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework", "frameworkB.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("with sdk dependencies") { $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .sdk(root: nil), reference: "sdkA.framework", embed: true), Dependency(type: .sdk(root: nil), reference: "sdkB.framework", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["System/Library/Frameworks/sdkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .sdk(root: nil), reference: "sdkA.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .sdk(root: nil), reference: "sdkB.framework", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["System/Library/Frameworks/sdkA.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("with package dependencies") { let packages: [String: SwiftPackage] = [ "RxSwift": .remote(url: "https://github.com/ReactiveX/RxSwift", versionRequirement: .upToNextMajorVersion("5.1.1")), ] $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .package(product: "RxSwift"), reference: "RxSwift", embed: true), Dependency(type: .package(product: "RxCocoa"), reference: "RxSwift", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [], packages: packages) // then try expectCopyPhase(in: pbxProject, withProductPaths: ["RxSwift"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .package(product: "RxSwift"), reference: "RxSwift", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .package(product: "RxCocoa"), reference: "RxSwift", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: [], packages: packages) // then try expectCopyPhase(in: pbxProject, withProductPaths: ["RxSwift"], toSubFolder: .plugins, dstPath: "test") } } $0.context("with carthage dependencies") { $0.it("embeds them into frameworks without copy phase spec") { // given let dependencies = [ Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "frameworkA.framework", embed: true), Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "frameworkB.framework", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .frameworks, dstPath: "") } $0.it("embeds them into custom location with copy phase spec") { // given let dependencies = [ Dependency(type: .carthage(findFrameworks: false, linkType: .dynamic), reference: "frameworkA.framework", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .carthage(findFrameworks: false, linkType: .static), reference: "frameworkB.framework", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then try expectCopyPhase(in: pbxProject, withFilePaths: ["frameworkA.framework"], toSubFolder: .plugins, dstPath: "test") } } $0.context("with bundle dependencies") { $0.it("embeds them into resources without copy phase spec") { // given let dependencies = [ Dependency(type: .bundle, reference: "bundleA.bundle", embed: true), Dependency(type: .bundle, reference: "bundleB.bundle", embed: false), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then /// XcodeGen ignores embed: false for bundles try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.bundle", "bundleB.bundle"], toSubFolder: .resources) } $0.it("ignores custom copy phase spec") { // given let dependencies = [ Dependency(type: .bundle, reference: "bundleA.bundle", embed: true, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), Dependency(type: .bundle, reference: "bundleB.bundle", embed: false, copyPhase: BuildPhaseSpec.CopyFilesSettings(destination: .plugins, subpath: "test", phaseOrder: .postCompile)), ] // when let pbxProject = try generateProjectForApp(withDependencies: dependencies, targets: []) // then /// XcodeGen ignores embed: false for bundles try expectCopyPhase(in: pbxProject, withFilePaths: ["bundleA.bundle", "bundleB.bundle"], toSubFolder: .resources) } } } } } private extension PBXTarget { var carthageCopyFrameworkBuildPhase: PBXShellScriptBuildPhase? { buildPhases.first(where: { $0.name() == "Carthage" }) as? PBXShellScriptBuildPhase } }
mit
306bd34fa32d7c2247fb1f8477d1f7ce
50.634004
254
0.484121
5.666228
false
true
false
false
jjuster/JSSAlertView
Example/Tests/Tests.swift
1
1179
// https://github.com/Quick/Quick import Quick import Nimble import JSSAlertView class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
b7541dde79465472b09557de8225405b
22.46
63
0.364876
5.455814
false
false
false
false
panjinqiang11/Swift-WeiBo
WeiBo/WeiBo/Class/View/Compose/EmotionKeyBoard/PJKeyBoardBar.swift
1
2995
// // PJKeyBoardBar.swift // WeiBo // // Created by 潘金强 on 16/7/21. // Copyright © 2016年 潘金强. All rights reserved. // import UIKit enum EmotionType :Int { case Normal = 1000 case Emoji = 1001 case Lxh = 1002 } class PJKeyBoardBar: UIStackView { //上次点击的button var lastSelectedButton :UIButton? var selectButton: ((type: EmotionType) -> Void)? override init(frame: CGRect) { super.init(frame: frame) setUpUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUpUI(){ axis = .Horizontal distribution = .FillEqually addButton("默认", imageName: "compose_emotion_table_left",type: .Normal) addButton("Emoji", imageName: "compose_emotion_table_mid",type: .Emoji) addButton("浪小花", imageName: "compose_emotion_table_right",type: .Lxh) } private func addButton(title:String, imageName: String ,type:EmotionType) { let button = UIButton() button.tag = type.rawValue button.addTarget(self, action: "clikButtonAction:", forControlEvents: .TouchUpInside) button.setTitle(title, forState: .Normal) button.setTitleColor(UIColor.whiteColor(), forState: .Normal) button.setTitleColor(UIColor.redColor(), forState: .Selected) button.titleLabel?.font = UIFont.systemFontOfSize(15) // 设置背景图片 button.setBackgroundImage(UIImage(named: imageName + "_normal"), forState: .Normal) button.setBackgroundImage(UIImage(named: imageName + "_selected"), forState: .Selected) button.titleLabel?.font = UIFont.systemFontOfSize(15) //取消高亮 button.adjustsImageWhenHighlighted = false addArrangedSubview(button) if type == .Normal { lastSelectedButton?.selected = false button.selected = true lastSelectedButton = button } } @objc private func clikButtonAction(button :UIButton){ if button == lastSelectedButton { return } lastSelectedButton?.selected = false button.selected = true lastSelectedButton = button let type = EmotionType(rawValue: button.tag)! selectButton?(type: type) } func seleButton(section: Int){ let button = viewWithTag(section + 1000) as! UIButton if lastSelectedButton == button{ return }else { lastSelectedButton?.selected = false button.selected = true lastSelectedButton = button } } }
mit
09b473d8ba6dca4c9225a3686d70562c
24.344828
95
0.558163
5.157895
false
false
false
false
peterb12/nand2tetris
src/Hack Assembler/Hack Assembler/Assembler.swift
1
3538
// // Assembler.swift // Hack Assembler // // Created by peterb on 12/29/16. // Copyright © 2016 peterb. All rights reserved. // import Foundation enum AsmCommandType { case A_COMMAND; case C_COMMAND; case L_COMMAND; } func padTo(size : Int, inString : String) -> String { var paddedString = inString for _ in 0..<(size - inString.characters.count) { paddedString = "0" + paddedString } return paddedString } class Assembler { var symbolTable : [String:Int] = Dictionary() var romCounter : Int = 0 var ramCounter : Int = 0 var parser : Parser var coder : Code init(asmFile : String) { self.parser = Parser(asmFile: asmFile) self.coder = Code() } func buildSymbolTable() { while parser.hasMoreCommands() { if (parser.commandType() == AsmCommandType.L_COMMAND) { // Add item to symbol table. let symbol = parser.symbol() symbolTable[symbol] = romCounter } else { romCounter += 1 } parser.advance() } // Preload RAM table with R0..R15 for f in 0..<16 { symbolTable["R" + String(f)] = f } symbolTable["SP"] = 0 symbolTable["LCL"] = 1 symbolTable["ARG"] = 2 symbolTable["THIS"] = 3 symbolTable["THAT"] = 4 symbolTable["SCREEN"] = 16384 symbolTable["KBD"] = 24576 ramCounter = 16 } func assemble(asmFile : String) -> String { var machineCode : String = "" buildSymbolTable() parser.reset() while parser.hasMoreCommands() { let cmdType = parser.commandType() if (cmdType == AsmCommandType.A_COMMAND) { let symbol = parser.symbol() var maybeAddress : Int? = Int(symbol, radix: 10) let binString : String if let address = maybeAddress { // Yay, it's numeric, forge on ahead. binString = String(Int(address), radix: 2) } else { // Booo, we have to look it up. if let lookupAddress = symbolTable[symbol] { // a hit! binString = String(Int(lookupAddress), radix: 2) } else { // Booooooo, cache miss. Add a new symbol. symbolTable[symbol] = ramCounter binString = String(Int(ramCounter), radix: 2) ramCounter += 1 } } machineCode.append(padTo(size: 16, inString: binString)) machineCode.append("\n") } else if (cmdType == AsmCommandType.C_COMMAND) { let rawDest = parser.dest() let dest = coder.dest(inDest: rawDest) let rawComputation = parser.comp() let computation = coder.comp(inComp: rawComputation) let rawJump = parser.jump() let jump = coder.jump(inJump: rawJump) let binString = "111" + computation + dest + jump assert(binString.characters.count == 16, "Wrong number of bits in command.") machineCode.append(binString) machineCode.append("\n") } // L-Commands are no-ops at this point. parser.advance() } return machineCode } }
bsd-3-clause
d8a1ce9fb9d0babab5c7cc3f1d55a4a6
30.864865
92
0.510319
4.404732
false
false
false
false
ijoshsmith/swift-tic-tac-toe
Framework/TicTacToeTests/AI/GameBoard+DSL.swift
1
1172
// // GameBoard+DSL.swift // TicTacToe // // Created by Joshua Smith on 11/30/15. // Copyright © 2015 iJoshSmith. All rights reserved. // import Foundation func board3x3(diagramLines: String...) -> GameBoard { let diagram = diagramLines.joinWithSeparator("") return GameBoard.gameBoardFrom3x3TextDiagram(diagram) } /** Supports a simple domain-specific language for creating a GameBoard. */ extension GameBoard { static func gameBoardFrom3x3TextDiagram(textDiagram: String) -> GameBoard { assert(textDiagram.characters.count == 9) let board = GameBoard(), symbols = textDiagram.characters.map { String($0).uppercaseString }, marks = symbols.map(markFromSymbol) for (index, mark) in marks.enumerate() where mark != nil { let position = GameBoard.Position(row: index / 3, column: index % 3) board.putMark(mark!, atPosition: position) } return board } private static func markFromSymbol(symbol: String) -> Mark? { switch symbol { case "X": return .X case "O": return .O default: return nil } } }
mit
1897eff8f079cde3f3d67e80b1dc7b45
29.025641
80
0.632792
4.108772
false
false
false
false
gavrix/ImageViewModel
Carthage/Checkouts/ReactiveSwift/ReactiveSwift.playground/Pages/Property.xcplaygroundpage/Contents.swift
2
9440
/*: > # IMPORTANT: To use `ReactiveSwift.playground`, please: 1. Retrieve the project dependencies using one of the following terminal commands from the ReactiveSwift project root directory: - `git submodule update --init` **OR**, if you have [Carthage](https://github.com/Carthage/Carthage) installed - `carthage checkout` 1. Open `ReactiveSwift.xcworkspace` 1. Build `Result-Mac` scheme 1. Build `ReactiveSwift-macOS` scheme 1. Finally open the `ReactiveSwift.playground` 1. Choose `View > Show Debug Area` */ import Result import ReactiveSwift import Foundation /*: ## Property A **property**, represented by the [`PropertyProtocol`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Property.swift) , stores a value and notifies observers about future changes to that value. - The current value of a property can be obtained from the `value` getter. - The `producer` getter returns a [signal producer](SignalProductr) that will send the property’s current value, followed by all changes over time. - The `signal` getter returns a [signal](Signal) that will send all changes over time, but not the initial value. */ scopedExample("Creation") { let mutableProperty = MutableProperty(1) // The value of the property can be accessed via its `value` attribute print("Property has initial value \(mutableProperty.value)") // The properties value can be observed via its `producer` or `signal attribute` // Note, how the `producer` immediately sends the initial value, but the `signal` only sends new values mutableProperty.producer.startWithValues { print("mutableProperty.producer receied \($0)") } mutableProperty.signal.observeValues { print("mutableProperty.signal received \($0)") } print("---") print("Setting new value for mutableProperty: 2") mutableProperty.value = 2 print("---") // If a property should be exposed for readonly access, it can be wrapped in a Property let property = Property(mutableProperty) print("Reading value of readonly property: \(property.value)") property.signal.observeValues { print("property.signal received \($0)") } // Its not possible to set the value of a Property // readonlyProperty.value = 3 // But you can still change the value of the mutableProperty and observe its change on the property print("---") print("Setting new value for mutableProperty: 3") mutableProperty.value = 3 // Constant properties can be created by using the `Property(value:)` initializer let constant = Property(value: 1) // constant.value = 2 // The value of a constant property can not be changed } /*: ### Binding The `<~` operator can be used to bind properties in different ways. Note that in all cases, the target has to be a binding target, represented by the [`BindingTargetProtocol`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/UnidirectionalBinding.swift). All mutable property types, represented by the [`MutablePropertyProtocol`](https://github.com/ReactiveCocoa/ReactiveSwift/blob/master/Sources/Property.swift#L28), are inherently binding targets. * `property <~ signal` binds a [signal](#signals) to the property, updating the property’s value to the latest value sent by the signal. * `property <~ producer` starts the given [signal producer](#signal-producers), and binds the property’s value to the latest value sent on the started signal. * `property <~ otherProperty` binds one property to another, so that the destination property’s value is updated whenever the source property is updated. */ scopedExample("Binding from SignalProducer") { let producer = SignalProducer<Int, NoError> { observer, _ in print("New subscription, starting operation") observer.send(value: 1) observer.send(value: 2) } let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } // Notice how the producer will start the work as soon it is bound to the property property <~ producer } scopedExample("Binding from Signal") { let (signal, observer) = Signal<Int, NoError>.pipe() let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } property <~ signal print("Sending new value on signal: 1") observer.send(value: 1) print("Sending new value on signal: 2") observer.send(value: 2) } scopedExample("Binding from other Property") { let property = MutableProperty(0) property.producer.startWithValues { print("Property received \($0)") } let otherProperty = MutableProperty(0) // Notice how property receives another value of 0 as soon as the binding is established property <~ otherProperty print("Setting new value for otherProperty: 1") otherProperty.value = 1 print("Setting new value for otherProperty: 2") otherProperty.value = 2 } /*: ### Transformations Properties provide a number of transformations like `map`, `combineLatest` or `zip` for manipulation similar to [signal](Signal) and [signal producer](SignalProducer) */ scopedExample("`map`") { let property = MutableProperty(0) let mapped = property.map { $0 * 2 } mapped.producer.startWithValues { print("Mapped property received \($0)") } print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 2") property.value = 2 } scopedExample("`skipRepeats`") { let property = MutableProperty(0) let skipRepeatsProperty = property.skipRepeats() property.producer.startWithValues { print("Property received \($0)") } skipRepeatsProperty.producer.startWithValues { print("Skip-Repeats property received \($0)") } print("Setting new value for property: 0") property.value = 0 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 0") property.value = 0 } scopedExample("`uniqueValues`") { let property = MutableProperty(0) let unique = property.uniqueValues() property.producer.startWithValues { print("Property received \($0)") } unique.producer.startWithValues { print("Unique values property received \($0)") } print("Setting new value for property: 0") property.value = 0 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 1") property.value = 1 print("Setting new value for property: 0") property.value = 0 } scopedExample("`combineLatest`") { let propertyA = MutableProperty(0) let propertyB = MutableProperty("A") let combined = propertyA.combineLatest(with: propertyB) combined.producer.startWithValues { print("Combined property received \($0)") } print("Setting new value for propertyA: 1") propertyA.value = 1 print("Setting new value for propertyB: 'B'") propertyB.value = "B" print("Setting new value for propertyB: 'C'") propertyB.value = "C" print("Setting new value for propertyB: 'D'") propertyB.value = "D" print("Setting new value for propertyA: 2") propertyA.value = 2 } scopedExample("`zip`") { let propertyA = MutableProperty(0) let propertyB = MutableProperty("A") let zipped = propertyA.zip(with: propertyB) zipped.producer.startWithValues { print("Zipped property received \($0)") } print("Setting new value for propertyA: 1") propertyA.value = 1 print("Setting new value for propertyB: 'B'") propertyB.value = "B" // Observe that, in contrast to `combineLatest`, setting a new value for propertyB does not cause a new value for the zipped property until propertyA has a new value as well print("Setting new value for propertyB: 'C'") propertyB.value = "C" print("Setting new value for propertyB: 'D'") propertyB.value = "D" print("Setting new value for propertyA: 2") propertyA.value = 2 } scopedExample("`flatten`") { let property1 = MutableProperty("0") let property2 = MutableProperty("A") let property3 = MutableProperty("!") let property = MutableProperty(property1) // Try different merge strategies and see how the results change property.flatten(.latest).producer.startWithValues { print("Flattened property receive \($0)") } print("Sending new value on property1: 1") property1.value = "1" print("Sending new value on property: property2") property.value = property2 print("Sending new value on property1: 2") property1.value = "2" print("Sending new value on property2: B") property2.value = "B" print("Sending new value on property1: 3") property1.value = "3" print("Sending new value on property: property3") property.value = property3 print("Sending new value on property3: ?") property3.value = "?" print("Sending new value on property2: C") property2.value = "C" print("Sending new value on property1: 4") property1.value = "4" }
mit
16e8fd0e6d433eb047f833f9a209bae7
33.549451
388
0.681828
4.461684
false
false
false
false
6ag/WeiboSwift-mvvm
WeiboSwift/Classes/View/Home/StatusCell/StatusPictureView.swift
1
3656
// // StatusPictureView.swift // WeiboSwift // // Created by zhoujianfeng on 2017/1/21. // Copyright © 2017年 周剑峰. All rights reserved. // import UIKit class StatusPictureView: UIView { /// 配图视图高度约束 @IBOutlet weak var heightConstrait: NSLayoutConstraint! /// 微博视图模型 var viewModel: StatusViewModel? { didSet { calcViewSize() urls = viewModel?.picUrls } } /// 微博配图模型数组 private var urls: [StatusPicture]? { didSet { guard let urls = urls else { return } // 默认隐藏全部 for subview in subviews { subview.isHidden = true } var index = 0 for url in urls { let imageView = subviews[index] as? UIImageView imageView?.isHidden = false imageView?.setImage(urlString: url.thumbnail_pic, placeholderImage: nil) // 4张图的时候需要2行2列显示 if index == 1 && urls.count == 4 { index += 2 } else { index += 1 } } } } /// 根据视图模型的配图视图尺寸,调整内容显示 private func calcViewSize() { // 单图和多图第一张图片尺寸需要更新 if viewModel?.picUrls?.count == 1 { var fistSize = viewModel?.pictureViewSize ?? CGSize() fistSize.height -= STATUS_PICTURE_VIEW_OUTER_MARGIN subviews.first?.frame = CGRect(x: 0, y: STATUS_PICTURE_VIEW_OUTER_MARGIN, width: fistSize.width, height: fistSize.height) } else { subviews.first?.frame = CGRect(x: 0, y: STATUS_PICTURE_VIEW_OUTER_MARGIN, width: STATUS_PICTURE_ITEM_WIDTH, height: STATUS_PICTURE_ITEM_WIDTH) } // 修改高度约束 heightConstrait.constant = viewModel?.pictureViewSize.height ?? 0 } override func awakeFromNib() { super.awakeFromNib() prepareUI() } } // MARK: - 设置界面 extension StatusPictureView { /// 准备UI fileprivate func prepareUI() { // 超出边界的不显示 clipsToBounds = true // 背景颜色 backgroundColor = superview?.backgroundColor // 每行3列 let count = 3 let rect = CGRect(x: 0, y: STATUS_PICTURE_VIEW_OUTER_MARGIN, width: STATUS_PICTURE_ITEM_WIDTH, height: STATUS_PICTURE_ITEM_WIDTH) for i in 0..<count * count { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true let row = CGFloat(i / count) let col = CGFloat(i % count) let xOffset = col * (STATUS_PICTURE_ITEM_WIDTH + STATUS_PICTURE_VIEW_INNER_MARGIN) let yOffset = row * (STATUS_PICTURE_ITEM_WIDTH + STATUS_PICTURE_VIEW_INNER_MARGIN) imageView.frame = rect.offsetBy(dx: xOffset, dy: yOffset) addSubview(imageView) } } }
mit
b6ba315e2472d87f8490c373ef083122
27.932773
94
0.469068
4.842475
false
false
false
false
chaoyang805/DoubanMovie
DoubanMovie/RatingBar.swift
1
4196
/* * Copyright 2016 chaoyang805 [email protected] * * 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 class RatingBar: UIView { /// 电影的评分信息 var ratingScore: Float? { didSet { changeRatingBarAppearence() } } /// 保存五个star private var stars: [StarLayer] = [] /// 显示电影评分的label private var scoreLabel: UILabel? override func awakeFromNib() { super.awakeFromNib() // 添加五个默认的star addStars() // 添加label addScoreLabel() } private func addStars() { for index in 0...4 { let starLayer = StarLayer(frame: CGRect(x: 0, y: 0, width: 16, height: 16), appearence: .full) let width = starLayer.frame.width starLayer.frame.origin = CGPoint(x: CGFloat(index) * width, y: 0) stars.append(starLayer) self.layer.addSublayer(starLayer) } } private func addScoreLabel() { scoreLabel = UILabel() scoreLabel!.text = "\(10.0)" scoreLabel!.font = UIFont(name: "PingFang SC", size: 12) scoreLabel!.textColor = UIColor(red: 1.0, green: 0.678, blue: 0.043, alpha: 1) scoreLabel!.frame = CGRect(origin: CGPoint(x: 82, y: 1), size: (scoreLabel!.text! as NSString) .size(attributes: [NSFontAttributeName: scoreLabel!.font])) addSubview(scoreLabel!) } private func changeRatingBarAppearence() { guard let ratingScore = ratingScore else { return } let appearenceArray = [StarLayerAppearence](repeating: .full, count: 5) let yellowStarCount = Int(ratingScore / 2) for index in 0..<appearenceArray.count { if index < yellowStarCount { if stars[index].appearence != .full { let frame = stars[index].frame stars[index].removeFromSuperlayer() let newStar = StarLayer(frame: frame, appearence: .full) stars[index] = newStar self.layer.addSublayer(newStar) } else { continue } } else if index == yellowStarCount { let frame = stars[index].frame stars[index].removeFromSuperlayer() let newStar = StarLayer(frame: frame, appearence: middleStarType(ratingScore)) stars[index] = newStar self.layer.addSublayer(newStar) } else { let frame = stars[index].frame stars[index].removeFromSuperlayer() let newStar = StarLayer(frame: frame, appearence: .empty) stars[index] = newStar self.layer.addSublayer(newStar) } } scoreLabel?.text = "\(ratingScore)" } /// 是否需要显示半星,ratingScore / 2 后的小数部分在(0.1, 0.6]之间的需要显示半星,[0, 0.1]显示空星,(0.6,1)显示满星 private func hasHalfStar(ratingScore: Float) -> Bool { let a = Int(ratingScore * 100) / 2 % 100 return 10 < a && a < 60 } private func middleStarType(_ ratingScore: Float) -> StarLayerAppearence { let a = Int(ratingScore * 100) / 2 % 100 if 10 < a && a < 60 { return .half } else if 0 < a && a <= 10 { return .empty } else { return .full } } }
apache-2.0
1af73707d4daeb3a54a776b34a15f94c
32.073171
106
0.548918
4.407367
false
false
false
false
chaoyang805/DoubanMovie
DoubanMovie/MovieDetailViewController.swift
1
6882
/* * Copyright 2016 chaoyang805 [email protected] * * 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 ObjectMapper import AWPercentDrivenInteractiveTransition class MovieDetailViewController: UIViewController { // MARK: - Properties fileprivate lazy var doubanService: DoubanService = { return DoubanService.sharedService }() fileprivate lazy var realmHelper: RealmHelper = { return RealmHelper() }() fileprivate lazy var likedImage: UIImage = { return UIImage(named: "icon-liked")! }() fileprivate lazy var normalImage: UIImage = { return UIImage(named: "icon-like-normal")! }() var detailMovie: DoubanMovie? // MARK: - IBOutlets @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var artistsScrollView: UIScrollView! @IBOutlet weak var posterImageView: UIImageView! @IBOutlet weak var movieSummaryText: UITextView! @IBOutlet weak var movieTitleLabel: UILabel! @IBOutlet weak var movieCastsLabel: UILabel! @IBOutlet weak var movieGenresLabel: UILabel! @IBOutlet weak var movieCollectCountLabel: UILabel! @IBOutlet weak var movieDirectorLabel: UILabel! @IBOutlet weak var movieYearLabel: UILabel! @IBOutlet weak var likeBarButton: UIBarButtonItem! var percentDrivenInteractiveController: AWPercentDrivenInteractiveTransition! var shareElementPopTransition: ShareElementPopTransition! = ShareElementPopTransition() override func viewDidLoad() { super.viewDidLoad() queryMovieDetail() configureView() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) notifyObserver() } fileprivate var deleted: Bool = false private func notifyObserver() { NotificationCenter.default.post(name: DBMMovieDidDeleteNotificationName, object: nil, userInfo: [DBMMovieDeleteNotificationKey: deleted]) } @IBAction func favoriteBarButtonPressed(_ sender: UIBarButtonItem) { movieExistAtRealm() ? deleteMovieFromRealm() : addMovieToFavorite() } func configureView() { guard let movie = detailMovie else { return } let exists = realmHelper.movieExists(id: movie.id) if exists { likeBarButton.image = likedImage } posterImageView.sd_setImage(with: URL(string: movie.images!.largeImageURL), placeholderImage: UIImage(named: "placeholder")) navigationItem.title = movie.title movieTitleLabel.text = movie.title movieCastsLabel.text = movie.castsDescription movieDirectorLabel.text = movie.directorsDescription movieGenresLabel.text = movie.genres movieCollectCountLabel.text = String(format: "%d人看过",movie.collectCount) movieYearLabel.text = movie.year movieSummaryText.text = movie.summary // configure casts addAvatars(withMovie: movie) } func addAvatars(withMovie movie: DoubanMovie) { let artistCount = movie.directors.count + movie.casts.count artistsScrollView.contentSize = CGSize(width: CGFloat(artistCount) * (60 + 20), height: artistsScrollView.frame.height) artistsScrollView.showsVerticalScrollIndicator = false artistsScrollView.showsHorizontalScrollIndicator = false for (index, director) in movie.directors.enumerated() { guard let _ = director.avatars else { continue } addAvatarView(withCelebrity: director, at: index) } for (index, actor) in movie.casts.enumerated() { guard let _ = actor.avatars else { continue } addAvatarView(withCelebrity: actor, at: index + movie.directors.count) } } private let vSpacing: CGFloat = 20 private let width: CGFloat = 60 func addAvatarView(withCelebrity celebrity: DoubanCelebrity, at position: Int) { let position = CGPoint(x: CGFloat(position) * (width + vSpacing), y: 0) let avatarView = AvatarView(frame: CGRect(origin: position, size: CGSize(width: width, height: 90)), celebrity: celebrity) artistsScrollView.addSubview(avatarView) } func queryMovieDetail() { guard let movie = detailMovie, let id = detailMovie?.id else {return } /** * 如果summary不为空,说明已经更新过了 */ if !movie.summary.isEmpty { return } // 如果该条目是收藏的条目,直接从数据库中查询summary信息,不再请求网络 if movieExistAtRealm() { realmHelper.getFavoriteMovie(byId: id, completion: { [weak self](movie) in guard let `self` = self, let movie = movie else { return } self.detailMovie?.summary = movie.summary }) } else { loadMovieSummaryFromNetwork(byId:id) } } /** 从网络请求电影的summary - parameter id: 电影的id */ func loadMovieSummaryFromNetwork(byId id: String) { doubanService.movie(forId: id) { [weak self](responseJSON, error) in guard let `self` = self else { return } let updatedMovie = Mapper<DoubanMovie>().map(JSON: responseJSON!) self.detailMovie?.summary = updatedMovie?.summary ?? "暂无" self.movieSummaryText.text = self.detailMovie?.summary } } } // Modify Favorite Movie extension MovieDetailViewController { func movieExistAtRealm() -> Bool { guard let movie = detailMovie else { return false } return realmHelper.movieExists(id: movie.id) } /** 取消收藏当前页面的电影 */ func deleteMovieFromRealm() { guard let movieId = detailMovie?.id else { return } realmHelper.deleteMovieById(id: movieId) likeBarButton.image = normalImage deleted = true } func addMovieToFavorite() { guard let movie = detailMovie else { return } movie.collectDate = Date() realmHelper.addFavoriteMovie(movie, copy: true) likeBarButton.image = likedImage deleted = false } }
apache-2.0
c5dcb0a82e106517b9f3ad399f830411
32.7
145
0.652671
4.723196
false
false
false
false
vknabel/Taps
Sources/Taps/Tapes/ThrowingTape.swift
1
1453
import RxSwift import TestHarness public extension OfferingTaps { /// A tester for potentially throwing tests. /// /// - Parameter test: The name of the test. /// - Parameter plan: The amount of expected `TestPoint`s. /// Will automatically call `TestPoint.end` if all planned tests have been run. /// - Parameter directive: The `Directive` that shall be applied. If `TestPoint`s fail, they won't break the build. /// - Parameter timeout: The interval defining the maximum duration the test may need. /// - Parameter scheduler: The scheduler for the test. Visit RxSwift for more info. /// - Parameter test: A function that runs your tests. public func test( _ title: String? = nil, plan: Int? = nil, file: String = #file, line: Int = #line, column: Int = #column, function: String = #function, timeout interval: RxTimeInterval? = nil, scheduler: SchedulerType? = nil, with tests: @escaping (Test) throws -> Void ) { let location = SourceLocation(file: file, line: line, column: column, function: function) rx.assertionTest( title, source: location, timeout: interval, scheduler: scheduler ) { return Observable<TestPoint>.create { report in let test = Test(report: report, plan: plan) do { try tests(test) } catch { report.onError(error) } return Disposables.create { } } } } }
mit
dc28779286216045db6717e66ec1af02
32.790698
117
0.640743
4.236152
false
true
false
false
lamb/trials
llsfw/llsfw/OnlineViewController.swift
1
3605
// // OnlineViewController.swift // llsfw // // Created by Lamb on 16/3/7. // Copyright © 2016年 gm. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class OnlineViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var refreshControl = UIRefreshControl() var data: JSON? let url = "http://192.168.16.85:8080/llsfw-webdemo/api/ApiPortalController/loadOnlineSecctionData" // 处理点击事件 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("tableView click") } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let list = data?.arrayValue { return list.count } else { return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Table Cell", forIndexPath: indexPath) let item = data?.arrayValue[indexPath.row] cell.textLabel!.text = "HOST: \(item!["REMOTE_HOST"].stringValue), DATE: \(item!["SESSION_CREATE_DATE"].stringValue)" return cell } @IBAction func signout(sender: UIButton) { let viewController = storyboard?.instantiateViewControllerWithIdentifier("ViewController") as! ViewController viewController.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal self.presentViewController(viewController, animated: true, completion: nil) } func refreshData() { let userDefaults = NSUserDefaults.standardUserDefaults() let clientIdentity = userDefaults.stringForKey("clientIdentity")! let clientDigest = userDefaults.stringForKey("clientDigest")! let parameters = ["clientIdentity": clientIdentity, "clientDigest": clientDigest] //self.activityIndicatorView.startAnimating() Alamofire.request(.GET, url, parameters: parameters).responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let data = JSON(value)["result"] self.data = data print(data) } case .Failure(let error): print(error) let alert = UIAlertController(title: "错误", message: "网络错误", preferredStyle: UIAlertControllerStyle.Alert) self.presentViewController(alert, animated: true, completion: { () -> Void in alert.dismissViewControllerAnimated(true, completion: nil) }) } //self.activityIndicatorView.stopAnimating() self.tableView.reloadData() self.refreshControl.endRefreshing() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. tableView.delegate = self tableView.dataSource = self refreshControl.addTarget(self, action: "refreshData", forControlEvents: UIControlEvents.ValueChanged) refreshControl.attributedTitle = NSAttributedString(string: "松开后自动刷新") tableView.addSubview(refreshControl) refreshData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
efcc28e8a940aa45cb182dddb9bdb701
37.73913
125
0.650954
5.457887
false
false
false
false
mobgeek/swift
Swift em 4 Semanas/Playgrounds/Semana 3/2-Propriedades.playground/Contents.swift
2
3444
// Playground - noun: a place where people can play import UIKit // Instâncias de Estruturas como constantes struct AiPhoneEstrutura { //Propriedades: var versãoOS: Float let UDID: String } var umAiPhone = AiPhoneEstrutura(versãoOS: 7.0, UDID:"GFHTUN56HET546GDM9KJ") umAiPhone.versãoOS = 8.0 // umAiPhone.UDID = "" //Erro let segundoAiPhone = AiPhoneEstrutura(versãoOS: 8.0, UDID:"RTHTYN56HET546GDJUKJ") // segundoAiPhone.versãoOS = 7.0 // Isso irá reportar um erro, mesmo que versãoOS for declarado como uma variável. // Instâncias de Classes como constantes class AiPhoneClasse { var versãoOS = 7.0 let UDID = "" } let umOutroAiPhone = AiPhoneClasse() umOutroAiPhone.versãoOS = 8.0 umAiPhone // Lazy class ImportaDados { // vamos assumir que essa classe demora um pouquinho para inicializar. // Pode ser lento porque essa instância precisa abrir um arquivo e ler o seu conteúdo na memória enquanto a instância está sendo inicializada. let nomeDoArquivo = "dados.txt" // algumas outras funcionalidades aqui... } class MrDados { lazy var importa = ImportaDados() var dados = [String]() // algumas funcionalidades para gerenciar dados entrariam aqui... } let mister = MrDados() mister.dados.append("Alguns dados") mister.dados.append("Mais dados") // A instância de ImportaDados para a propriedade importa ainda não foi criada. mister.dados mister.importa.nomeDoArquivo //Aqui a instância de ImportaDados foi criada // Propriedades Computadas struct TriânguloEquilátero { var comprimentoLado: Double = 0.0 var perimêtro: Double { get { return 3.0 * comprimentoLado } set(novoLado) { comprimentoLado = novoLado / 3.0 } } } var triângulo = TriânguloEquilátero(comprimentoLado: 3.0) var perimetroTriangulo = triângulo.perimêtro //chamando o get triângulo.comprimentoLado = 9.9 //chamando o set // Propriedades Read-only struct Ortoedro { var altura = 0.0, largura = 0.0, profundidade = 0.0 var volume: Double { return altura*largura*profundidade } } let caixa = Ortoedro(altura: 3.0, largura: 2.0, profundidade: 8.0) caixa.volume //caixa.valume = 60 //Erro // Observadores de Propriedades class ContaPassos { var totalPassos: Int = 0 { willSet(novoTotalPassos) { println("Prestes a configurar totalPassos para \(novoTotalPassos) ") } didSet { if totalPassos > oldValue { println("\(totalPassos - oldValue) passos adicionados!") } } } } let contaPassos = ContaPassos() contaPassos.totalPassos = 500 // Prestes a configurar totalPassos para 200 // 200 passos adicioandos! contaPassos.totalPassos = 600 // Prestes a configurar totalPassos para 600 // 100 passos adicioandos! // Propriedades de Tipo struct umaEstrutura { static var propArmDoTipo = "Algum valor." static var propCompDoTipo: Int { return 1 } } class umaClasse { class var propCompDoTipo: Int { return 1 } } umaClasse.propCompDoTipo umaEstrutura.propArmDoTipo umaEstrutura.propArmDoTipo = "Outro valor." umaEstrutura.propArmDoTipo
mit
3508c52025960f1dea1796721eb43d38
15.261905
146
0.65183
3.051832
false
false
false
false
scuty2000/open-gestional-software
Open-Gestional-Software/ViewController.swift
1
110179
// // ViewController.swift // Open-Gestional-Software // // Created by Luca Scutigliani on 06/06/17. // Copyright © 2017 Scutigliani Luca. All rights reserved. // import Cocoa import WebKit class ViewController: NSViewController { //Box 1 (Home Page) [Main] @IBOutlet weak var box1: NSBox! //Box 2 (Add Page) [Hidden] {Enabled} @IBOutlet weak var box2: NSBox! //Box 3 (Remove Page) [Hidden] {Enabled} @IBOutlet weak var box3: NSBox! //Box 4 (Price Page) [Hidden] {Enabled} @IBOutlet weak var box4: NSBox! //Box 5 @IBOutlet weak var box5: NSBox! //WebView (Api Call) [Hidden] @IBOutlet weak var myView: WebView! @IBOutlet weak var myView2: WebView! @IBOutlet weak var myView3: WebView! @IBOutlet weak var myView4: WebView! @IBOutlet weak var myView5: WebView! @IBOutlet weak var myView6: WebView! @IBOutlet weak var myView7: WebView! @IBOutlet weak var myView8: WebView! @IBOutlet weak var myView9: WebView! @IBOutlet weak var myView10: WebView! @IBOutlet weak var myView11: WebView! @IBOutlet weak var myView12: WebView! @IBOutlet weak var myView13: WebView! @IBOutlet weak var myView14: WebView! //Campi Prenotazione Futura @IBOutlet weak var nomeStanzatextFut: NSComboBox! @IBOutlet weak var nomeClienteFut: NSTextField! @IBOutlet weak var cognomeClienteFut: NSTextField! @IBOutlet weak var cellulareClienteFut: NSTextField! @IBOutlet weak var emailClienteFut: NSTextField! @IBOutlet weak var data_InizioFut: NSTextField! @IBOutlet weak var data_FineFut: NSTextField! //Campi Prenotazione @IBOutlet weak var nomeStanzaText: NSComboBox! @IBOutlet weak var data_InizioText: NSTextField! @IBOutlet weak var data_FineText: NSTextField! @IBOutlet weak var nomeCognomeClienteText: NSTextField! //Campi Cliente @IBOutlet weak var nomeClienteText: NSTextField! @IBOutlet weak var cognomeClienteText: NSTextField! @IBOutlet weak var cellulareText: NSTextField! @IBOutlet weak var data_nascitaText: NSTextField! //Campo Rimozione Prenotazione @IBOutlet weak var nomeStanzaRemoveText: NSComboBox! //Campi Prezzo @IBOutlet weak var HalfDay1: NSTextField! @IBOutlet weak var Day1: NSTextField! @IBOutlet weak var Month1: NSTextField! @IBOutlet weak var HalfDay2: NSTextField! @IBOutlet weak var Day2: NSTextField! @IBOutlet weak var Month2: NSTextField! @IBOutlet weak var Halfday3: NSTextField! @IBOutlet weak var Day3: NSTextField! @IBOutlet weak var Month3: NSTextField! @IBOutlet weak var Halfday4: NSTextField! @IBOutlet weak var Day4: NSTextField! @IBOutlet weak var Month4: NSTextField! @IBOutlet weak var Halfday5: NSTextField! @IBOutlet weak var Day5: NSTextField! @IBOutlet weak var Month5: NSTextField! @IBOutlet weak var Halfday6: NSTextField! @IBOutlet weak var Day6: NSTextField! @IBOutlet weak var Month6: NSTextField! @IBOutlet weak var Halfday7: NSTextField! @IBOutlet weak var Day7: NSTextField! @IBOutlet weak var Month7: NSTextField! @IBOutlet weak var Halfday8: NSTextField! @IBOutlet weak var Day8: NSTextField! @IBOutlet weak var Month8: NSTextField! //Info Labels Room 1 @IBOutlet weak var nome1: NSTextField! @IBOutlet weak var postazioni1: NSTextField! @IBOutlet weak var disponibile1: NSTextField! @IBOutlet weak var prenotato1: NSTextField! @IBOutlet weak var prezzoHalfDay1: NSTextField! @IBOutlet weak var prezzoDay1: NSTextField! @IBOutlet weak var prezzoMonth1: NSTextField! //Info Labels Room 2 @IBOutlet weak var nome2: NSTextField! @IBOutlet weak var postazioni2: NSTextField! @IBOutlet weak var disponibile2: NSTextField! @IBOutlet weak var prenotato2: NSTextField! @IBOutlet weak var prezzoHalfDay2: NSTextField! @IBOutlet weak var prezzoDay2: NSTextField! @IBOutlet weak var prezzoMonth2: NSTextField! //Info Labels Room 3 @IBOutlet weak var nome3: NSTextField! @IBOutlet weak var postazioni3: NSTextField! @IBOutlet weak var disponibile3: NSTextField! @IBOutlet weak var prenotato3: NSTextField! @IBOutlet weak var prezzoHalfDay3: NSTextField! @IBOutlet weak var prezzoDay3: NSTextField! @IBOutlet weak var prezzoMonth3: NSTextField! //Info Labels Room 4 @IBOutlet weak var nome4: NSTextField! @IBOutlet weak var postazioni4: NSTextField! @IBOutlet weak var disponibile4: NSTextField! @IBOutlet weak var prenotato4: NSTextField! @IBOutlet weak var prezzoHalfDay4: NSTextField! @IBOutlet weak var prezzoDay4: NSTextField! @IBOutlet weak var prezzoMonth4: NSTextField! //Info Labels Room 5 @IBOutlet weak var nome5: NSTextField! @IBOutlet weak var postazioni5: NSTextField! @IBOutlet weak var disponibile5: NSTextField! @IBOutlet weak var prenotato5: NSTextField! @IBOutlet weak var prezzoHalfDay5: NSTextField! @IBOutlet weak var prezzoDay5: NSTextField! @IBOutlet weak var prezzoMonth5: NSTextField! //Info Labels Room 6 @IBOutlet weak var nome6: NSTextField! @IBOutlet weak var postazioni6: NSTextField! @IBOutlet weak var disponibile6: NSTextField! @IBOutlet weak var prenotato6: NSTextField! @IBOutlet weak var prezzoHalfDay6: NSTextField! @IBOutlet weak var prezzoDay6: NSTextField! @IBOutlet weak var prezzoMonth6: NSTextField! //Info Labels Room 7 @IBOutlet weak var nome7: NSTextField! @IBOutlet weak var postazioni7: NSTextField! @IBOutlet weak var disponibile7: NSTextField! @IBOutlet weak var prenotato7: NSTextField! @IBOutlet weak var prezzoHalfDay7: NSTextField! @IBOutlet weak var prezzoDay7: NSTextField! @IBOutlet weak var prezzoMonth7: NSTextField! //Info Labels Room 8 @IBOutlet weak var nome8: NSTextField! @IBOutlet weak var postazione8: NSTextField! @IBOutlet weak var disponibile8: NSTextField! @IBOutlet weak var prenotato8: NSTextField! @IBOutlet weak var prezzoHalfDay8: NSTextField! @IBOutlet weak var prezzoDay8: NSTextField! @IBOutlet weak var prezzoMonth8: NSTextField! //Info Fut Labels Room 1 @IBOutlet weak var prenID1: NSTextField! @IBOutlet weak var nomeCognomeFutInfo1: NSTextField! @IBOutlet weak var dataInzioFineFut1: NSTextField! @IBOutlet weak var contattiFut1: NSTextField! @IBOutlet weak var avanti1: NSButton! @IBOutlet weak var accetta1: NSButton! @IBOutlet weak var elimina1: NSButton! @IBOutlet weak var indietro1: NSButton! //Info Fut Labels Room 2 @IBOutlet weak var prenID2: NSTextField! @IBOutlet weak var nomeCognomeFutInfo2: NSTextField! @IBOutlet weak var dataInizioFineFut2: NSTextField! @IBOutlet weak var contattiFut2: NSTextField! @IBOutlet weak var avanti2: NSButton! @IBOutlet weak var indietro2: NSButton! @IBOutlet weak var accetta2: NSButton! @IBOutlet weak var elimina2: NSButton! //Info Fut Labels Room 3 @IBOutlet weak var prenID3: NSTextField! @IBOutlet weak var nomeCognomeFutInfo3: NSTextField! @IBOutlet weak var dataInizioFineFut3: NSTextField! @IBOutlet weak var contattiFut3: NSTextField! @IBOutlet weak var accetta3: NSButton! @IBOutlet weak var elimina3: NSButton! @IBOutlet weak var indietro3: NSButton! @IBOutlet weak var avanti3: NSButton! //Info Fut Labels Room 4 @IBOutlet weak var prenID4: NSTextField! @IBOutlet weak var nomeCognomeFutInfo4: NSTextField! @IBOutlet weak var dataInizioFineFut4: NSTextField! @IBOutlet weak var contattiFut4: NSTextField! @IBOutlet weak var accetta4: NSButton! @IBOutlet weak var elimina4: NSButton! @IBOutlet weak var indietro4: NSButton! @IBOutlet weak var avanti4: NSButton! @IBOutlet weak var accetta5: NSButton! //Info Fut Labels Room 5 @IBOutlet weak var prenID5: NSTextField! @IBOutlet weak var nomeCognomeFutInfo5: NSTextField! @IBOutlet weak var dataInizioFineFut5: NSTextField! @IBOutlet weak var contattiFut5: NSTextField! @IBOutlet weak var indietro5: NSButton! @IBOutlet weak var elimina5: NSButton! @IBOutlet weak var avanti5: NSButton! //Info Lables Fut Room 6 @IBOutlet weak var prenID6: NSTextField! @IBOutlet weak var nomeCognomeFutInfo6: NSTextField! @IBOutlet weak var dataInizioFineFut6: NSTextField! @IBOutlet weak var contattiFut6: NSTextField! @IBOutlet weak var indietro6: NSButton! @IBOutlet weak var avanti6: NSButton! @IBOutlet weak var accetta6: NSButton! @IBOutlet weak var elimina6: NSButton! //Info Fut Lables Room 7 @IBOutlet weak var prenID7: NSTextField! @IBOutlet weak var nomeCognomeFutInfo7: NSTextField! @IBOutlet weak var indietro7: NSButton! @IBOutlet weak var dataInizioFineFut7: NSTextField! @IBOutlet weak var contattiFut7: NSTextField! @IBOutlet weak var avanti7: NSButton! @IBOutlet weak var accetta7: NSButton! @IBOutlet weak var elimina7: NSButton! //Info Fut Labels Room 8 @IBOutlet weak var prenID8: NSTextField! @IBOutlet weak var nomeCognomeFutInfo8: NSTextField! @IBOutlet weak var indietro8: NSButton! @IBOutlet weak var dataInizioFineFut8: NSTextField! @IBOutlet weak var contattiFut8: NSTextField! @IBOutlet weak var avanti8: NSButton! @IBOutlet weak var accetta8: NSButton! @IBOutlet weak var elimina8: NSButton! //Variabili Globali var esecuzioneFetch : Int = 0 var currentIndex1 : Int = 0 var currentIndex2 : Int = 0 var currentIndex3 : Int = 0 var currentIndex4 : Int = 0 var currentIndex5 : Int = 0 var currentIndex6 : Int = 0 var currentIndex7 : Int = 0 var currentIndex8 : Int = 0 override func viewDidLoad() { super.viewDidLoad() // self.box2.isHidden = true // self.box3.isHidden = true // self.box4.isHidden = true // self.box5.isHidden = true _ = self.fetch() _ = self.checkFut1() _ = self.checkFut2() _ = self.checkFut3() _ = self.checkFut4() _ = self.checkFut5() _ = self.checkFut6() _ = self.checkFut7() _ = self.checkFut8() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } //Dependency Functions func json_parseData(_ data: Data) -> NSDictionary? { do { let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) print("[JSON] OK!") print(json) return (json as? NSDictionary) } catch _ { print("[ERROR] An error has happened with parsing of json data") return nil } } func data_request(forData: String) -> Data? { guard let url = URL(string: "http://127.0.0.1/kds/api/\(forData)") else { return nil } guard let data = try? Data(contentsOf: url) else { print("[ERROR] There is an unspecified error with the connection") return nil } print("[CONNECTION] OK, data correctly downloaded") return data } //New Functions func fetch() { myView.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch.php")!)) let data = data_request(forData: "fetch.json") _ = json_parseData(data!) if let json = json_parseData(data!) { let data_array: NSArray = (json["stored"] as? NSArray)! let uff1: NSDictionary = data_array[0] as! NSDictionary let uff2: NSDictionary = data_array[1] as! NSDictionary let uff3: NSDictionary = data_array[2] as! NSDictionary let uff4: NSDictionary = data_array[3] as! NSDictionary let uff5: NSDictionary = data_array[4] as! NSDictionary let uff6: NSDictionary = data_array[5] as! NSDictionary let uff7: NSDictionary = data_array[6] as! NSDictionary let uff8: NSDictionary = data_array[7] as! NSDictionary //Inizio Pannello 1 let postazioni1testo : String = "Postazioni: \(((uff1["postazioni"] as? String!)!)!)" if (((uff1["disponibile"] as? String!)!)! == "1"){ let disponibile1testo : String = "Disponibile" // print("[DEBUGGING] Disponibile") disponibile1.stringValue = disponibile1testo } else { let disponibile1testo : String = "Non disponibile" // print("[DEBUGGING] Non disponibile") disponibile1.stringValue = disponibile1testo } if (((uff1["data_inizio_prenotazione"] as? String!)!)! == "00/00/0000" && ((uff1["data_fine_prenotazione"] as? String!)!)! == "00/00/0000") { let prenotato1testo = " - " // print("[DEBUGGING] - ") prenotato1.stringValue = prenotato1testo } else { let prenotato1testo = "Dal: \(((uff1["data_inizio_prenotazione"] as? String!)!)!) al: \(((uff1["data_fine_prenotazione"] as? String!)!)!)" // print("[DEBUGGING] Date ok") prenotato1.stringValue = prenotato1testo } let prezzoHalfDay1testo = "\(((uff1["prezzoMezzoGiorno"] as? String!)!)!)€ per 1/2 Giorno" let prezzoDay1testo = "\(((uff1["prezzoGiorno"] as? String!)!)!)€ al giorno" let prezzoMonth1testo = "\(((uff1["prezzoMese"] as? String!)!)!)€ al Mese" nome1.stringValue = (uff1["nome"] as? String!)! postazioni1.stringValue = postazioni1testo prezzoHalfDay1.stringValue = prezzoHalfDay1testo prezzoDay1.stringValue = prezzoDay1testo prezzoMonth1.stringValue = prezzoMonth1testo //Fine Pannello 1 //Inizio Pannello 2 let postazioni2testo : String = "Postazioni: \(((uff2["postazioni"] as? String!)!)!)" if (((uff2["disponibile"] as? String!)!)! == "1"){ let disponibile2testo : String = "Disponibile" // print("[DEBUGGING] Disponibile") disponibile2.stringValue = disponibile2testo } else { let disponibile2testo : String = "Non disponibile" // print("[DEBUGGING] Non disponibile") disponibile2.stringValue = disponibile2testo } if (((uff2["data_inizio_prenotazione"] as? String!)!)! == "00/00/0000" && ((uff2["data_fine_prenotazione"] as? String!)!)! == "00/00/0000") { let prenotato2testo = " - " // print("[DEBUGGING] - ") prenotato2.stringValue = prenotato2testo } else { let prenotato2testo = "Dal: \(((uff2["data_inizio_prenotazione"] as? String!)!)!) al: \(((uff2["data_fine_prenotazione"] as? String!)!)!)" // print("[DEBUGGING] Date ok") prenotato2.stringValue = prenotato2testo } let prezzoHalfDay2testo = "\(((uff2["prezzoMezzoGiorno"] as? String!)!)!)€ per 1/2 Giorno" let prezzoDay2testo = "\(((uff2["prezzoGiorno"] as? String!)!)!)€ al giorno" let prezzoMonth2testo = "\(((uff2["prezzoMese"] as? String!)!)!)€ al Mese" nome2.stringValue = (uff2["nome"] as? String!)! postazioni2.stringValue = postazioni2testo prezzoHalfDay2.stringValue = prezzoHalfDay2testo prezzoDay2.stringValue = prezzoDay2testo prezzoMonth2.stringValue = prezzoMonth2testo //Fine Pannello 2 //Inizio Pannello 3 let postazioni3testo : String = "Postazioni: \(((uff3["postazioni"] as? String!)!)!)" if (((uff3["disponibile"] as? String!)!)! == "1"){ let disponibile3testo : String = "Disponibile" // print("[DEBUGGING] Disponibile") disponibile3.stringValue = disponibile3testo } else { let disponibile3testo : String = "Non disponibile" // print("[DEBUGGING] Non disponibile") disponibile3.stringValue = disponibile3testo } if (((uff3["data_inizio_prenotazione"] as? String!)!)! == "00/00/0000" && ((uff3["data_fine_prenotazione"] as? String!)!)! == "00/00/0000") { let prenotato3testo = " - " // print("[DEBUGGING] - ") prenotato3.stringValue = prenotato3testo } else { let prenotato3testo = "Dal: \(((uff3["data_inizio_prenotazione"] as? String!)!)!) al: \(((uff3["data_fine_prenotazione"] as? String!)!)!)" // print("[DEBUGGING] Date ok") prenotato3.stringValue = prenotato3testo } let prezzoHalfDay3testo = "\(((uff3["prezzoMezzoGiorno"] as? String!)!)!)€ per 1/2 Giorno" let prezzoDay3testo = "\(((uff3["prezzoGiorno"] as? String!)!)!)€ al giorno" let prezzoMonth3testo = "\(((uff3["prezzoMese"] as? String!)!)!)€ al Mese" nome3.stringValue = (uff3["nome"] as? String!)! postazioni3.stringValue = postazioni3testo prezzoHalfDay3.stringValue = prezzoHalfDay3testo prezzoDay3.stringValue = prezzoDay3testo prezzoMonth3.stringValue = prezzoMonth3testo //Fine Pannello 3 //Inizio Pannello 4 let postazioni4testo : String = "Postazioni: \(((uff4["postazioni"] as? String!)!)!)" if (((uff4["disponibile"] as? String!)!)! == "1"){ let disponibile4testo : String = "Disponibile" // print("[DEBUGGING] Disponibile") disponibile4.stringValue = disponibile4testo } else { let disponibile4testo : String = "Non disponibile" // print("[DEBUGGING] Non disponibile") disponibile4.stringValue = disponibile4testo } if (((uff4["data_inizio_prenotazione"] as? String!)!)! == "00/00/0000" && ((uff4["data_fine_prenotazione"] as? String!)!)! == "00/00/0000") { let prenotato4testo = " - " // print("[DEBUGGING] - ") prenotato4.stringValue = prenotato4testo } else { let prenotato4testo = "Dal: \(((uff4["data_inizio_prenotazione"] as? String!)!)!) al: \(((uff4["data_fine_prenotazione"] as? String!)!)!)" // print("[DEBUGGING] Date ok") prenotato4.stringValue = prenotato4testo } let prezzoHalfDay4testo = "\(((uff4["prezzoMezzoGiorno"] as? String!)!)!)€ per 1/2 Giorno" let prezzoDay4testo = "\(((uff4["prezzoGiorno"] as? String!)!)!)€ al giorno" let prezzoMonth4testo = "\(((uff4["prezzoMese"] as? String!)!)!)€ al Mese" nome4.stringValue = (uff4["nome"] as? String!)! postazioni4.stringValue = postazioni4testo prezzoHalfDay4.stringValue = prezzoHalfDay4testo prezzoDay4.stringValue = prezzoDay4testo prezzoMonth4.stringValue = prezzoMonth4testo //Fine Pannello 4 //Inizio Pannello 5 let postazioni5testo : String = "Postazioni: \(((uff5["postazioni"] as? String!)!)!)" if (((uff5["disponibile"] as? String!)!)! == "1"){ let disponibile5testo : String = "Disponibile" // print("[DEBUGGING] Disponibile") disponibile5.stringValue = disponibile5testo } else { let disponibile5testo : String = "Non disponibile" // print("[DEBUGGING] Non disponibile") disponibile5.stringValue = disponibile5testo } if (((uff5["data_inizio_prenotazione"] as? String!)!)! == "00/00/0000" && ((uff5["data_fine_prenotazione"] as? String!)!)! == "00/00/0000") { let prenotato5testo = " - " // print("[DEBUGGING] - ") prenotato5.stringValue = prenotato5testo } else { let prenotato5testo = "Dal: \(((uff5["data_inizio_prenotazione"] as? String!)!)!) al: \(((uff5["data_fine_prenotazione"] as? String!)!)!)" // print("[DEBUGGING] Date ok") prenotato5.stringValue = prenotato5testo } let prezzoHalfDay5testo = "\(((uff5["prezzoMezzoGiorno"] as? String!)!)!)€ per 1/2 Giorno" let prezzoDay5testo = "\(((uff5["prezzoGiorno"] as? String!)!)!)€ al giorno" let prezzoMonth5testo = "\(((uff5["prezzoMese"] as? String!)!)!)€ al Mese" nome5.stringValue = (uff5["nome"] as? String!)! postazioni5.stringValue = postazioni5testo prezzoHalfDay5.stringValue = prezzoHalfDay5testo prezzoDay5.stringValue = prezzoDay5testo prezzoMonth5.stringValue = prezzoMonth5testo //Fine Pannello 5 //Inizio Pannello 6 let postazioni6testo : String = "Postazioni: \(((uff6["postazioni"] as? String!)!)!)" if (((uff6["disponibile"] as? String!)!)! == "1"){ let disponibile6testo : String = "Disponibile" // print("[DEBUGGING] Disponibile") disponibile6.stringValue = disponibile6testo } else { let disponibile6testo : String = "Non disponibile" // print("[DEBUGGING] Non disponibile") disponibile6.stringValue = disponibile6testo } if (((uff6["data_inizio_prenotazione"] as? String!)!)! == "00/00/0000" && ((uff6["data_fine_prenotazione"] as? String!)!)! == "00/00/0000") { let prenotato6testo = " - " // print("[DEBUGGING] - ") prenotato6.stringValue = prenotato6testo } else { let prenotato6testo = "Dal: \(((uff6["data_inizio_prenotazione"] as? String!)!)!) al: \(((uff6["data_fine_prenotazione"] as? String!)!)!)" // print("[DEBUGGING] Date ok") prenotato6.stringValue = prenotato6testo } let prezzoHalfDay6testo = "\(((uff6["prezzoMezzoGiorno"] as? String!)!)!)€ per 1/2 Giorno" let prezzoDay6testo = "\(((uff6["prezzoGiorno"] as? String!)!)!)€ al giorno" let prezzoMonth6testo = "\(((uff6["prezzoMese"] as? String!)!)!)€ al Mese" nome6.stringValue = (uff6["nome"] as? String!)! postazioni6.stringValue = postazioni6testo prezzoHalfDay6.stringValue = prezzoHalfDay6testo prezzoDay6.stringValue = prezzoDay6testo prezzoMonth6.stringValue = prezzoMonth6testo //Fine Pannello 6 //Inizio Pannello 7 let postazioni7testo : String = "Postazioni: \(((uff7["postazioni"] as? String!)!)!)" if (((uff7["disponibile"] as? String!)!)! == "1"){ let disponibile7testo : String = "Disponibile" // print("[DEBUGGING] Disponibile") disponibile7.stringValue = disponibile7testo } else { let disponibile7testo : String = "Non disponibile" // print("[DEBUGGING] Non disponibile") disponibile7.stringValue = disponibile7testo } if (((uff7["data_inizio_prenotazione"] as? String!)!)! == "00/00/0000" && ((uff7["data_fine_prenotazione"] as? String!)!)! == "00/00/0000") { let prenotato7testo = " - " // print("[DEBUGGING] - ") prenotato7.stringValue = prenotato7testo } else { let prenotato7testo = "Dal: \(((uff7["data_inizio_prenotazione"] as? String!)!)!) al: \(((uff7["data_fine_prenotazione"] as? String!)!)!)" // print("[DEBUGGING] Date ok") prenotato7.stringValue = prenotato7testo } let prezzoHalfDay7testo = "\(((uff7["prezzoMezzoGiorno"] as? String!)!)!)€ per 1/2 Giorno" let prezzoDay7testo = "\(((uff7["prezzoGiorno"] as? String!)!)!)€ al giorno" nome7.stringValue = (uff7["nome"] as? String!)! postazioni7.stringValue = postazioni7testo prezzoHalfDay7.stringValue = prezzoHalfDay7testo prezzoDay7.stringValue = prezzoDay7testo //Fine Pannello 7 //Inizio Pannello 8 let postazioni8testo : String = "Postazioni: \(((uff8["postazioni"] as? String!)!)!)" if (((uff8["disponibile"] as? String!)!)! == "1"){ let disponibile8testo : String = "Disponibile" // print("[DEBUGGING] Disponibile") disponibile8.stringValue = disponibile8testo } else { let disponibile8testo : String = "Non disponibile" // print("[DEBUGGING] Non disponibile") disponibile8.stringValue = disponibile8testo } if (((uff8["data_inizio_prenotazione"] as? String!)!)! == "00/00/0000" && ((uff8["data_fine_prenotazione"] as? String!)!)! == "00/00/0000") { let prenotato8testo = " - " // print("[DEBUGGING] - ") prenotato8.stringValue = prenotato8testo } else { let prenotato8testo = "Dal: \(((uff8["data_inizio_prenotazione"] as? String!)!)!) al: \(((uff8["data_fine_prenotazione"] as? String!)!)!)" // print("[DEBUGGING] Date ok") prenotato8.stringValue = prenotato8testo } let prezzoHalfDay8testo = "\(((uff8["prezzoMezzoGiorno"] as? String!)!)!)€ per 1/2 Giorno" let prezzoDay8testo = "\(((uff8["prezzoGiorno"] as? String!)!)!)€ al giorno" nome8.stringValue = (uff8["nome"] as? String!)! postazione8.stringValue = postazioni8testo prezzoHalfDay8.stringValue = prezzoHalfDay8testo prezzoDay8.stringValue = prezzoDay8testo //Fine Pannello8 } self.esecuzioneFetch = self.esecuzioneFetch + 1 print("[DEBUGGING] Fetch #\(esecuzioneFetch)") let when = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when) { _ = self.fetch() } } func addPren() { let id = (nomeStanzaText.indexOfSelectedItem) + 1 let data_Inizio = data_InizioText.stringValue let data_Fine = data_FineText.stringValue let nomeCognomeCliente = nomeCognomeClienteText.stringValue self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prenotazione&id=\(id)&startDate=\(data_Inizio)&endDate=\(data_Fine)&cliente=\(nomeCognomeCliente)")!)) } func addCliente() { let nomeCliente = nomeClienteText.stringValue let cognomeCliente = cognomeClienteText.stringValue let cellulare = cellulareText.stringValue let data_nascita = data_nascitaText.stringValue self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=utente&nome=\(nomeCliente)&cognome=\(cognomeCliente)&cellulare=\(cellulare)&data_nascita=\(data_nascita)&disp=0")!)) } func removePren() { let id = (nomeStanzaRemoveText.indexOfSelectedItem) + 1 self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prenotazione&id=\(id)&startDate=00/00/0000&endDate=00/00/0000&cliente=&disp=1")!)) } @IBAction func showHomePage(_ sender: Any) { self.box2.isHidden = true self.box3.isHidden = true self.box4.isHidden = true self.box5.isHidden = true } @IBAction func showAddPage(_ sender: Any) { self.box2.isHidden = false self.box3.isHidden = true self.box4.isHidden = true self.box5.isHidden = true } @IBAction func showRemovePage(_ sender: Any) { self.box3.isHidden = false self.box4.isHidden = true self.box5.isHidden = true } @IBAction func showPricePage(_ sender: Any) { self.box4.isHidden = false self.box5.isHidden = true } @IBAction func addPrenButton(_ sender: Any) { _ = addPren() } @IBAction func addCliente(_ sender: Any) { _ = addCliente() } @IBAction func removePrenButton(_ sender: Any) { _ = removePren() } @IBAction func change1Button(_ sender: Any) { let HalfDay1var = HalfDay1.stringValue let Day1var = Day1.stringValue let Month1var = Month1.stringValue if (HalfDay1var != ""){ self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMezGiorno&id=1&prezzo=\(HalfDay1var)")!)) } if (Day1var != ""){ self.myView3.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoGiorno&id=1&prezzo=\(Day1var)")!)) } if (Month1var != ""){ self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMese&id=1&prezzo=\(Month1var)")!)) } } @IBAction func change2Button(_ sender: Any) { let HalfDay2var = HalfDay2.stringValue let Day2var = Day2.stringValue let Month2var = Month2.stringValue if (HalfDay2var != ""){ self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMezGiorno&id=2&prezzo=\(HalfDay2var)")!)) } if (Day2var != ""){ self.myView3.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoGiorno&id=2&prezzo=\(Day2var)")!)) } if (Month2var != ""){ self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMese&id=2&prezzo=\(Month2var)")!)) } } @IBAction func change3Button(_ sender: Any) { let HalfDay3var = Halfday3.stringValue let Day3var = Day3.stringValue let Month3var = Month3.stringValue if (HalfDay3var != ""){ self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMezGiorno&id=3&prezzo=\(HalfDay3var)")!)) } if (Day3var != ""){ self.myView3.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoGiorno&id=3&prezzo=\(Day3var)")!)) } if (Month3var != ""){ self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMese&id=3&prezzo=\(Month3var)")!)) } } @IBAction func change4Button(_ sender: Any) { let HalfDay4var = Halfday4.stringValue let Day4var = Day4.stringValue let Month4var = Month4.stringValue if (HalfDay4var != ""){ self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMezGiorno&id=4&prezzo=\(HalfDay4var)")!)) } if (Day4var != ""){ self.myView3.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoGiorno&id=4&prezzo=\(Day4var)")!)) } if (Month4var != ""){ self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMese&id=4&prezzo=\(Month4var)")!)) } } @IBAction func change5Button(_ sender: Any) { let HalfDay5var = Halfday5.stringValue let Day5var = Day5.stringValue let Month5var = Month5.stringValue if (HalfDay5var != ""){ self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMezGiorno&id=5&prezzo=\(HalfDay5var)")!)) } if (Day5var != ""){ self.myView3.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoGiorno&id=5&prezzo=\(Day5var)")!)) } if (Month5var != ""){ self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMese&id=5&prezzo=\(Month5var)")!)) } } @IBAction func change6Button(_ sender: Any) { let HalfDay6var = Halfday6.stringValue let Day6var = Day6.stringValue let Month6var = Month6.stringValue if (HalfDay6var != ""){ self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMezGiorno&id=6&prezzo=\(HalfDay6var)")!)) } if (Day6var != ""){ self.myView3.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoGiorno&id=6&prezzo=\(Day6var)")!)) } if (Month6var != ""){ self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMese&id=6&prezzo=\(Month6var)")!)) } } @IBAction func change7Button(_ sender: Any) { let HalfDay7var = Halfday7.stringValue let Day7var = Day7.stringValue let Month7var = Month7.stringValue if (HalfDay7var != ""){ self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMezGiorno&id=7&prezzo=\(HalfDay7var)")!)) } if (Day7var != ""){ self.myView3.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoGiorno&id=7&prezzo=\(Day7var)")!)) } if (Month7var != ""){ self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMese&id=7&prezzo=\(Month7var)")!)) } } @IBAction func change8button(_ sender: Any) { let HalfDay8var = Halfday8.stringValue let Day8var = Day8.stringValue let Month8var = Month8.stringValue if (HalfDay8var != ""){ self.myView2.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMezGiorno&id=8&prezzo=\(HalfDay8var)")!)) } if (Day8var != ""){ self.myView3.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoGiorno&id=8&prezzo=\(Day8var)")!)) } if (Month8var != ""){ self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=prezzoMese&id=8&prezzo=\(Month8var)")!)) } } @IBAction func addPrenFut(_ sender: Any) { self.myView4.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/addPren.php?nome=\(nomeClienteFut.stringValue)&email=\(emailClienteFut.stringValue)&ufficio=\(nomeStanzatextFut.indexOfSelectedItem+1)&cognome=\(cognomeClienteFut.stringValue)&dataEnd=\(data_FineFut.stringValue)&cellulare=\(cellulareClienteFut.stringValue)&dataStart=\(data_InizioFut.stringValue)")!)) } @IBAction func accettaPrenFut1(_ sender: Any) { let id_pren1 = prenID1.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=accettazione&stanza=1&id_pren=\(id_pren1)")!)) } @IBAction func elimina1(_ sender: Any) { let id_pren1 = prenID1.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=eliminazione&id_pren=\(id_pren1)")!)) } @IBAction func avanti1Button(_ sender: Any) { self.currentIndex1 = currentIndex1 + 1 } @IBAction func indietro1Button(_ sender: Any) { self.currentIndex1 = currentIndex1 - 1 } func checkFut1 () { myView6.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch2.php?idStanza=1")!)) let dataFut = data_request(forData: "stanza1.json") _ = json_parseData(dataFut!) if let json1 = json_parseData(dataFut!) { let data_array1: NSArray = (json1["data"] as? NSArray)! var total1 = 0 for _ in data_array1 { total1 = total1 + 1 } if total1 == 0 { prenID1.stringValue = "-"; nomeCognomeFutInfo1.stringValue = "Non ci sono prenotazioni"; dataInzioFineFut1.stringValue = "-" contattiFut1.stringValue = "-" avanti1.isHidden = true accetta1.isHidden = true elimina1.isHidden = true indietro1.isHidden = true } else { if total1 == 1 { elimina1.isHidden = false let Stanza1Dic: NSDictionary = data_array1[0] as! NSDictionary prenID1.stringValue = (Stanza1Dic["id_prenotazione"] as? String!)!; let stringaCliente1 = "\(((Stanza1Dic["nome"] as? String!)!)!) \(((Stanza1Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo1.stringValue = stringaCliente1 let dateFutu1 = "\(((Stanza1Dic["data_iniziale"] as? String!)!)!) - \(((Stanza1Dic["data_finale"] as? String!)!)!)" dataInzioFineFut1.stringValue = dateFutu1 let contattiCliente1 = "\(((Stanza1Dic["email"] as? String!)!)!) ≈ \(((Stanza1Dic["cellulare"] as? String!)!)!)" contattiFut1.stringValue = contattiCliente1 if(((Stanza1Dic["accettata"] as? String!)!)! == "0") { self.accetta1.isHidden = false } else { self.accetta1.isHidden = true } avanti1.isHidden = true indietro1.isHidden = true } else { if (total1 > (currentIndex1+1) && currentIndex1 != 0) { avanti1.isHidden = false indietro1.isHidden = false elimina1.isHidden = false let Stanza1Dic: NSDictionary = data_array1[currentIndex1] as! NSDictionary prenID1.stringValue = (Stanza1Dic["id_prenotazione"] as? String!)!; let stringaCliente1 = "\(((Stanza1Dic["nome"] as? String!)!)!) \(((Stanza1Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo1.stringValue = stringaCliente1 let dateFutu1 = "\(((Stanza1Dic["data_iniziale"] as? String!)!)!) - \(((Stanza1Dic["data_finale"] as? String!)!)!)" dataInzioFineFut1.stringValue = dateFutu1 let contattiCliente1 = "\(((Stanza1Dic["email"] as? String!)!)!) ≈ \(((Stanza1Dic["cellulare"] as? String!)!)!)" contattiFut1.stringValue = contattiCliente1 if(((Stanza1Dic["accettata"] as? String!)!)! == "0") { self.accetta1.isHidden = false } else { self.accetta1.isHidden = true } } else { if(currentIndex1 == 0) { avanti1.isHidden = false indietro1.isHidden = true elimina1.isHidden = false let Stanza1Dic: NSDictionary = data_array1[currentIndex1] as! NSDictionary prenID1.stringValue = (Stanza1Dic["id_prenotazione"] as? String!)!; let stringaCliente1 = "\(((Stanza1Dic["nome"] as? String!)!)!) \(((Stanza1Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo1.stringValue = stringaCliente1 let dateFutu1 = "\(((Stanza1Dic["data_iniziale"] as? String!)!)!) - \(((Stanza1Dic["data_finale"] as? String!)!)!)" dataInzioFineFut1.stringValue = dateFutu1 let contattiCliente1 = "\(((Stanza1Dic["email"] as? String!)!)!) ≈ \(((Stanza1Dic["cellulare"] as? String!)!)!)" contattiFut1.stringValue = contattiCliente1 if(((Stanza1Dic["accettata"] as? String!)!)! == "0") { self.accetta1.isHidden = false } else { self.accetta1.isHidden = true } } else { if (total1 == (currentIndex1+1)) { avanti1.isHidden = true indietro1.isHidden = false elimina1.isHidden = false let Stanza1Dic: NSDictionary = data_array1[currentIndex1] as! NSDictionary prenID1.stringValue = (Stanza1Dic["id_prenotazione"] as? String!)!; let stringaCliente1 = "\(((Stanza1Dic["nome"] as? String!)!)!) \(((Stanza1Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo1.stringValue = stringaCliente1 let dateFutu1 = "\(((Stanza1Dic["data_iniziale"] as? String!)!)!) - \(((Stanza1Dic["data_finale"] as? String!)!)!)" dataInzioFineFut1.stringValue = dateFutu1 let contattiCliente1 = "\(((Stanza1Dic["email"] as? String!)!)!) ≈ \(((Stanza1Dic["cellulare"] as? String!)!)!)" contattiFut1.stringValue = contattiCliente1 if(((Stanza1Dic["accettata"] as? String!)!)! == "0") { self.accetta1.isHidden = false } else { self.accetta1.isHidden = true } } } } } } } let when1 = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when1) { _ = self.checkFut1() } } //Fine Pannello 1 //Inizio Pannello 2 func checkFut2 () { myView8.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch2.php?idStanza=2")!)) let dataFut2 = data_request(forData: "stanza2.json") _ = json_parseData(dataFut2!) if let json2 = json_parseData(dataFut2!) { let data_array2: NSArray = (json2["data"] as? NSArray)! var total2 = 0 for _ in data_array2 { total2 = total2 + 1 } if total2 == 0 { prenID2.stringValue = "-"; nomeCognomeFutInfo2.stringValue = "Non ci sono prenotazioni"; dataInizioFineFut2.stringValue = "-" contattiFut2.stringValue = "-" avanti2.isHidden = true accetta2.isHidden = true elimina2.isHidden = true indietro2.isHidden = true } else { if total2 == 1 { elimina2.isHidden = false let Stanza2Dic: NSDictionary = data_array2[0] as! NSDictionary prenID2.stringValue = (Stanza2Dic["id_prenotazione"] as? String!)!; let stringaCliente2 = "\(((Stanza2Dic["nome"] as? String!)!)!) \(((Stanza2Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo2.stringValue = stringaCliente2 let dateFutu2 = "\(((Stanza2Dic["data_iniziale"] as? String!)!)!) - \(((Stanza2Dic["data_finale"] as? String!)!)!)" dataInizioFineFut2.stringValue = dateFutu2 let contattiCliente2 = "\(((Stanza2Dic["email"] as? String!)!)!) ≈ \(((Stanza2Dic["cellulare"] as? String!)!)!)" contattiFut2.stringValue = contattiCliente2 if(((Stanza2Dic["accettata"] as? String!)!)! == "0") { self.accetta2.isHidden = false } else { self.accetta2.isHidden = true } avanti2.isHidden = true indietro2.isHidden = true } else { if (total2 > (currentIndex2+1) && currentIndex2 != 0) { avanti2.isHidden = false indietro2.isHidden = false elimina2.isHidden = false let Stanza2Dic: NSDictionary = data_array2[currentIndex2] as! NSDictionary prenID2.stringValue = (Stanza2Dic["id_prenotazione"] as? String!)!; let stringaCliente2 = "\(((Stanza2Dic["nome"] as? String!)!)!) \(((Stanza2Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo2.stringValue = stringaCliente2 let dateFutu2 = "\(((Stanza2Dic["data_iniziale"] as? String!)!)!) - \(((Stanza2Dic["data_finale"] as? String!)!)!)" dataInizioFineFut2.stringValue = dateFutu2 let contattiCliente2 = "\(((Stanza2Dic["email"] as? String!)!)!) ≈ \(((Stanza2Dic["cellulare"] as? String!)!)!)" contattiFut2.stringValue = contattiCliente2 if(((Stanza2Dic["accettata"] as? String!)!)! == "0") { self.accetta2.isHidden = false } else { self.accetta2.isHidden = true } } else { if(currentIndex2 == 0) { avanti2.isHidden = false indietro2.isHidden = true elimina2.isHidden = false let Stanza2Dic: NSDictionary = data_array2[currentIndex2] as! NSDictionary prenID2.stringValue = (Stanza2Dic["id_prenotazione"] as? String!)!; let stringaCliente2 = "\(((Stanza2Dic["nome"] as? String!)!)!) \(((Stanza2Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo2.stringValue = stringaCliente2 let dateFutu2 = "\(((Stanza2Dic["data_iniziale"] as? String!)!)!) - \(((Stanza2Dic["data_finale"] as? String!)!)!)" dataInizioFineFut2.stringValue = dateFutu2 let contattiCliente2 = "\(((Stanza2Dic["email"] as? String!)!)!) ≈ \(((Stanza2Dic["cellulare"] as? String!)!)!)" contattiFut2.stringValue = contattiCliente2 if(((Stanza2Dic["accettata"] as? String!)!)! == "0") { self.accetta2.isHidden = false } else { self.accetta2.isHidden = true } } else { if (total2 == (currentIndex2+1)) { avanti2.isHidden = true indietro2.isHidden = false elimina2.isHidden = false let Stanza2Dic: NSDictionary = data_array2[currentIndex2] as! NSDictionary prenID2.stringValue = (Stanza2Dic["id_prenotazione"] as? String!)!; let stringaCliente2 = "\(((Stanza2Dic["nome"] as? String!)!)!) \(((Stanza2Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo2.stringValue = stringaCliente2 let dateFutu2 = "\(((Stanza2Dic["data_iniziale"] as? String!)!)!) - \(((Stanza2Dic["data_finale"] as? String!)!)!)" dataInizioFineFut2.stringValue = dateFutu2 let contattiCliente2 = "\(((Stanza2Dic["email"] as? String!)!)!) ≈ \(((Stanza2Dic["cellulare"] as? String!)!)!)" contattiFut2.stringValue = contattiCliente2 if(((Stanza2Dic["accettata"] as? String!)!)! == "0") { self.accetta2.isHidden = false } else { self.accetta2.isHidden = true } } } } } } } let when2 = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when2) { _ = self.checkFut2() } } //Fine Pannello 2 //Inizio Pannello 3 func checkFut3 () { myView9.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch2.php?idStanza=3")!)) let dataFut3 = data_request(forData: "stanza3.json") _ = json_parseData(dataFut3!) if let json3 = json_parseData(dataFut3!) { let data_array3: NSArray = (json3["data"] as? NSArray)! var total3 = 0 for _ in data_array3 { total3 = total3 + 1 } if total3 == 0 { prenID3.stringValue = "-"; nomeCognomeFutInfo3.stringValue = "Non ci sono prenotazioni"; dataInizioFineFut3.stringValue = "-" contattiFut3.stringValue = "-" avanti3.isHidden = true accetta3.isHidden = true elimina3.isHidden = true indietro3.isHidden = true } else { if total3 == 1 { elimina3.isHidden = false let Stanza3Dic: NSDictionary = data_array3[0] as! NSDictionary prenID3.stringValue = (Stanza3Dic["id_prenotazione"] as? String!)!; let stringaCliente3 = "\(((Stanza3Dic["nome"] as? String!)!)!) \(((Stanza3Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo3.stringValue = stringaCliente3 let dateFutu3 = "\(((Stanza3Dic["data_iniziale"] as? String!)!)!) - \(((Stanza3Dic["data_finale"] as? String!)!)!)" dataInizioFineFut3.stringValue = dateFutu3 let contattiCliente3 = "\(((Stanza3Dic["email"] as? String!)!)!) ≈ \(((Stanza3Dic["cellulare"] as? String!)!)!)" contattiFut3.stringValue = contattiCliente3 if(((Stanza3Dic["accettata"] as? String!)!)! == "0") { self.accetta3.isHidden = false } else { self.accetta3.isHidden = true } avanti3.isHidden = true indietro3.isHidden = true } else { if (total3 > (currentIndex3+1) && currentIndex3 != 0) { avanti3.isHidden = false indietro3.isHidden = false elimina3.isHidden = false let Stanza3Dic: NSDictionary = data_array3[currentIndex3] as! NSDictionary prenID3.stringValue = (Stanza3Dic["id_prenotazione"] as? String!)!; let stringaCliente3 = "\(((Stanza3Dic["nome"] as? String!)!)!) \(((Stanza3Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo3.stringValue = stringaCliente3 let dateFutu3 = "\(((Stanza3Dic["data_iniziale"] as? String!)!)!) - \(((Stanza3Dic["data_finale"] as? String!)!)!)" dataInizioFineFut3.stringValue = dateFutu3 let contattiCliente3 = "\(((Stanza3Dic["email"] as? String!)!)!) ≈ \(((Stanza3Dic["cellulare"] as? String!)!)!)" contattiFut3.stringValue = contattiCliente3 if(((Stanza3Dic["accettata"] as? String!)!)! == "0") { self.accetta3.isHidden = false } else { self.accetta3.isHidden = true } } else { if(currentIndex3 == 0) { avanti3.isHidden = false indietro3.isHidden = true elimina3.isHidden = false let Stanza3Dic: NSDictionary = data_array3[currentIndex3] as! NSDictionary prenID3.stringValue = (Stanza3Dic["id_prenotazione"] as? String!)!; let stringaCliente3 = "\(((Stanza3Dic["nome"] as? String!)!)!) \(((Stanza3Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo3.stringValue = stringaCliente3 let dateFutu3 = "\(((Stanza3Dic["data_iniziale"] as? String!)!)!) - \(((Stanza3Dic["data_finale"] as? String!)!)!)" dataInizioFineFut3.stringValue = dateFutu3 let contattiCliente3 = "\(((Stanza3Dic["email"] as? String!)!)!) ≈ \(((Stanza3Dic["cellulare"] as? String!)!)!)" contattiFut3.stringValue = contattiCliente3 if(((Stanza3Dic["accettata"] as? String!)!)! == "0") { self.accetta3.isHidden = false } else { self.accetta3.isHidden = true } } else { if (total3 == (currentIndex3+1)) { avanti3.isHidden = true indietro3.isHidden = false elimina3.isHidden = false let Stanza3Dic: NSDictionary = data_array3[currentIndex3] as! NSDictionary prenID3.stringValue = (Stanza3Dic["id_prenotazione"] as? String!)!; let stringaCliente3 = "\(((Stanza3Dic["nome"] as? String!)!)!) \(((Stanza3Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo3.stringValue = stringaCliente3 let dateFutu3 = "\(((Stanza3Dic["data_iniziale"] as? String!)!)!) - \(((Stanza3Dic["data_finale"] as? String!)!)!)" dataInizioFineFut3.stringValue = dateFutu3 let contattiCliente3 = "\(((Stanza3Dic["email"] as? String!)!)!) ≈ \(((Stanza3Dic["cellulare"] as? String!)!)!)" contattiFut3.stringValue = contattiCliente3 if(((Stanza3Dic["accettata"] as? String!)!)! == "0") { self.accetta3.isHidden = false } else { self.accetta3.isHidden = true } } } } } } } let when3 = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when3) { _ = self.checkFut3() } } func checkFut4 () { myView10.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch2.php?idStanza=4")!)) let dataFut4 = data_request(forData: "stanza4.json") _ = json_parseData(dataFut4!) if let json4 = json_parseData(dataFut4!) { let data_array4: NSArray = (json4["data"] as? NSArray)! var total4 = 0 for _ in data_array4 { total4 = total4 + 1 } if total4 == 0 { prenID4.stringValue = "-"; nomeCognomeFutInfo4.stringValue = "Non ci sono prenotazioni"; dataInizioFineFut4.stringValue = "-" contattiFut4.stringValue = "-" avanti4.isHidden = true accetta4.isHidden = true elimina4.isHidden = true indietro4.isHidden = true } else { if total4 == 1 { elimina4.isHidden = false let Stanza4Dic: NSDictionary = data_array4[0] as! NSDictionary prenID4.stringValue = (Stanza4Dic["id_prenotazione"] as? String!)!; let stringaCliente4 = "\(((Stanza4Dic["nome"] as? String!)!)!) \(((Stanza4Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo4.stringValue = stringaCliente4 let dateFutu4 = "\(((Stanza4Dic["data_iniziale"] as? String!)!)!) - \(((Stanza4Dic["data_finale"] as? String!)!)!)" dataInizioFineFut4.stringValue = dateFutu4 let contattiCliente4 = "\(((Stanza4Dic["email"] as? String!)!)!) ≈ \(((Stanza4Dic["cellulare"] as? String!)!)!)" contattiFut4.stringValue = contattiCliente4 if(((Stanza4Dic["accettata"] as? String!)!)! == "0") { self.accetta4.isHidden = false } else { self.accetta4.isHidden = true } avanti4.isHidden = true indietro4.isHidden = true } else { if (total4 > (currentIndex4+1) && currentIndex4 != 0) { avanti4.isHidden = false indietro4.isHidden = false elimina4.isHidden = false let Stanza4Dic: NSDictionary = data_array4[currentIndex4] as! NSDictionary prenID4.stringValue = (Stanza4Dic["id_prenotazione"] as? String!)!; let stringaCliente4 = "\(((Stanza4Dic["nome"] as? String!)!)!) \(((Stanza4Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo4.stringValue = stringaCliente4 let dateFutu4 = "\(((Stanza4Dic["data_iniziale"] as? String!)!)!) - \(((Stanza4Dic["data_finale"] as? String!)!)!)" dataInizioFineFut4.stringValue = dateFutu4 let contattiCliente4 = "\(((Stanza4Dic["email"] as? String!)!)!) ≈ \(((Stanza4Dic["cellulare"] as? String!)!)!)" contattiFut4.stringValue = contattiCliente4 if(((Stanza4Dic["accettata"] as? String!)!)! == "0") { self.accetta4.isHidden = false } else { self.accetta4.isHidden = true } } else { if(currentIndex4 == 0) { avanti4.isHidden = false indietro4.isHidden = true elimina4.isHidden = false let Stanza4Dic: NSDictionary = data_array4[currentIndex4] as! NSDictionary prenID4.stringValue = (Stanza4Dic["id_prenotazione"] as? String!)!; let stringaCliente4 = "\(((Stanza4Dic["nome"] as? String!)!)!) \(((Stanza4Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo4.stringValue = stringaCliente4 let dateFutu4 = "\(((Stanza4Dic["data_iniziale"] as? String!)!)!) - \(((Stanza4Dic["data_finale"] as? String!)!)!)" dataInizioFineFut4.stringValue = dateFutu4 let contattiCliente4 = "\(((Stanza4Dic["email"] as? String!)!)!) ≈ \(((Stanza4Dic["cellulare"] as? String!)!)!)" contattiFut4.stringValue = contattiCliente4 if(((Stanza4Dic["accettata"] as? String!)!)! == "0") { self.accetta4.isHidden = false } else { self.accetta4.isHidden = true } } else { if (total4 == (currentIndex4+1)) { avanti4.isHidden = true indietro4.isHidden = false elimina4.isHidden = false let Stanza4Dic: NSDictionary = data_array4[currentIndex4] as! NSDictionary prenID4.stringValue = (Stanza4Dic["id_prenotazione"] as? String!)!; let stringaCliente4 = "\(((Stanza4Dic["nome"] as? String!)!)!) \(((Stanza4Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo4.stringValue = stringaCliente4 let dateFutu4 = "\(((Stanza4Dic["data_iniziale"] as? String!)!)!) - \(((Stanza4Dic["data_finale"] as? String!)!)!)" dataInizioFineFut4.stringValue = dateFutu4 let contattiCliente4 = "\(((Stanza4Dic["email"] as? String!)!)!) ≈ \(((Stanza4Dic["cellulare"] as? String!)!)!)" contattiFut4.stringValue = contattiCliente4 if(((Stanza4Dic["accettata"] as? String!)!)! == "0") { self.accetta4.isHidden = false } else { self.accetta4.isHidden = true } } } } } } } let when4 = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when4) { _ = self.checkFut4() } } @IBAction func indietro2Button(_ sender: Any) { currentIndex2 = currentIndex2 - 1 } @IBAction func avanti2Button(_ sender: Any) { currentIndex2 = currentIndex2 + 1 } @IBAction func accetta2Button(_ sender: Any) { let id_pren2 = prenID2.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=accettazione&stanza=2&id_pren=\(id_pren2)")!)) } @IBAction func elimina2Button(_ sender: Any) { let id_pren2 = prenID2.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=eliminazione&id_pren=\(id_pren2)")!)) } @IBAction func indietro3Button(_ sender: Any) { currentIndex3 = currentIndex3 - 1 } @IBAction func avanti3Button(_ sender: Any) { currentIndex3 = currentIndex3 + 1 } @IBAction func accetta3Button(_ sender: Any) { let id_pren3 = prenID3.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=accettazione&stanza=2&id_pren=\(id_pren3)")!)) } @IBAction func elimina3Button(_ sender: Any) { let id_pren3 = prenID3.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=eliminazione&id_pren=\(id_pren3)")!)) } @IBAction func indietro4Button(_ sender: Any) { currentIndex4 = currentIndex4 - 1 } @IBAction func avanti4Button(_ sender: Any) { currentIndex4 = currentIndex4 + 1 } @IBAction func accetta4Button(_ sender: Any) { let id_pren4 = prenID4.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=accettazione&stanza=4&id_pren=\(id_pren4)")!)) } @IBAction func elimina4Button(_ sender: Any) { let id_pren4 = prenID4.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=eliminazione&id_pren=\(id_pren4)")!)) } @IBAction func indietro5Button(_ sender: Any) { currentIndex5 = currentIndex5 - 1 } @IBAction func avanti5Button(_ sender: Any) { currentIndex5 = currentIndex5 + 1 } @IBAction func accetta5Button(_ sender: Any) { let id_pren5 = prenID5.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=accettazione&stanza=5&id_pren=\(id_pren5)")!)) } @IBAction func elimina5Button(_ sender: Any) { let id_pren5 = prenID5.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=eliminazione&id_pren=\(id_pren5)")!)) } func checkFut5 () { myView11.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch2.php?idStanza=5")!)) let dataFut5 = data_request(forData: "stanza5.json") _ = json_parseData(dataFut5!) if let json5 = json_parseData(dataFut5!) { let data_array5: NSArray = (json5["data"] as? NSArray)! var total5 = 0 for _ in data_array5 { total5 = total5 + 1 } if total5 == 0 { prenID5.stringValue = "-"; nomeCognomeFutInfo5.stringValue = "Non ci sono prenotazioni"; dataInizioFineFut5.stringValue = "-" contattiFut5.stringValue = "-" avanti5.isHidden = true accetta5.isHidden = true elimina5.isHidden = true indietro5.isHidden = true } else { if total5 == 1 { elimina5.isHidden = false let Stanza5Dic: NSDictionary = data_array5[0] as! NSDictionary prenID5.stringValue = (Stanza5Dic["id_prenotazione"] as? String!)!; let stringaCliente5 = "\(((Stanza5Dic["nome"] as? String!)!)!) \(((Stanza5Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo5.stringValue = stringaCliente5 let dateFutu5 = "\(((Stanza5Dic["data_iniziale"] as? String!)!)!) - \(((Stanza5Dic["data_finale"] as? String!)!)!)" dataInizioFineFut5.stringValue = dateFutu5 let contattiCliente5 = "\(((Stanza5Dic["email"] as? String!)!)!) ≈ \(((Stanza5Dic["cellulare"] as? String!)!)!)" contattiFut5.stringValue = contattiCliente5 if(((Stanza5Dic["accettata"] as? String!)!)! == "0") { self.accetta5.isHidden = false } else { self.accetta5.isHidden = true } avanti5.isHidden = true indietro5.isHidden = true } else { if (total5 > (currentIndex5+1) && currentIndex5 != 0) { avanti5.isHidden = false indietro5.isHidden = false elimina5.isHidden = false let Stanza5Dic: NSDictionary = data_array5[currentIndex5] as! NSDictionary prenID5.stringValue = (Stanza5Dic["id_prenotazione"] as? String!)!; let stringaCliente5 = "\(((Stanza5Dic["nome"] as? String!)!)!) \(((Stanza5Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo5.stringValue = stringaCliente5 let dateFutu5 = "\(((Stanza5Dic["data_iniziale"] as? String!)!)!) - \(((Stanza5Dic["data_finale"] as? String!)!)!)" dataInizioFineFut5.stringValue = dateFutu5 let contattiCliente5 = "\(((Stanza5Dic["email"] as? String!)!)!) ≈ \(((Stanza5Dic["cellulare"] as? String!)!)!)" contattiFut5.stringValue = contattiCliente5 if(((Stanza5Dic["accettata"] as? String!)!)! == "0") { self.accetta5.isHidden = false } else { self.accetta5.isHidden = true } } else { if(currentIndex5 == 0) { avanti5.isHidden = false indietro5.isHidden = true elimina5.isHidden = false let Stanza5Dic: NSDictionary = data_array5[currentIndex5] as! NSDictionary prenID5.stringValue = (Stanza5Dic["id_prenotazione"] as? String!)!; let stringaCliente5 = "\(((Stanza5Dic["nome"] as? String!)!)!) \(((Stanza5Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo5.stringValue = stringaCliente5 let dateFutu5 = "\(((Stanza5Dic["data_iniziale"] as? String!)!)!) - \(((Stanza5Dic["data_finale"] as? String!)!)!)" dataInizioFineFut5.stringValue = dateFutu5 let contattiCliente5 = "\(((Stanza5Dic["email"] as? String!)!)!) ≈ \(((Stanza5Dic["cellulare"] as? String!)!)!)" contattiFut5.stringValue = contattiCliente5 if(((Stanza5Dic["accettata"] as? String!)!)! == "0") { self.accetta5.isHidden = false } else { self.accetta5.isHidden = true } } else { if (total5 == (currentIndex5+1)) { avanti5.isHidden = true indietro5.isHidden = false elimina5.isHidden = false let Stanza5Dic: NSDictionary = data_array5[currentIndex5] as! NSDictionary prenID5.stringValue = (Stanza5Dic["id_prenotazione"] as? String!)!; let stringaCliente5 = "\(((Stanza5Dic["nome"] as? String!)!)!) \(((Stanza5Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo5.stringValue = stringaCliente5 let dateFutu5 = "\(((Stanza5Dic["data_iniziale"] as? String!)!)!) - \(((Stanza5Dic["data_finale"] as? String!)!)!)" dataInizioFineFut5.stringValue = dateFutu5 let contattiCliente5 = "\(((Stanza5Dic["email"] as? String!)!)!) ≈ \(((Stanza5Dic["cellulare"] as? String!)!)!)" contattiFut5.stringValue = contattiCliente5 if(((Stanza5Dic["accettata"] as? String!)!)! == "0") { self.accetta5.isHidden = false } else { self.accetta5.isHidden = true } } } } } } } let when5 = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when5) { _ = self.checkFut5() } } func checkFut6 () { myView12.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch2.php?idStanza=6")!)) let dataFut6 = data_request(forData: "stanza6.json") _ = json_parseData(dataFut6!) if let json6 = json_parseData(dataFut6!) { let data_array6: NSArray = (json6["data"] as? NSArray)! var total6 = 0 for _ in data_array6 { total6 = total6 + 1 } if total6 == 0 { prenID6.stringValue = "-"; nomeCognomeFutInfo6.stringValue = "Non ci sono prenotazioni"; dataInizioFineFut6.stringValue = "-" contattiFut6.stringValue = "-" avanti6.isHidden = true accetta6.isHidden = true elimina6.isHidden = true indietro6.isHidden = true } else { if total6 == 1 { elimina6.isHidden = false let Stanza6Dic: NSDictionary = data_array6[0] as! NSDictionary prenID6.stringValue = (Stanza6Dic["id_prenotazione"] as? String!)!; let stringaCliente6 = "\(((Stanza6Dic["nome"] as? String!)!)!) \(((Stanza6Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo6.stringValue = stringaCliente6 let dateFutu6 = "\(((Stanza6Dic["data_iniziale"] as? String!)!)!) - \(((Stanza6Dic["data_finale"] as? String!)!)!)" dataInizioFineFut6.stringValue = dateFutu6 let contattiCliente6 = "\(((Stanza6Dic["email"] as? String!)!)!) ≈ \(((Stanza6Dic["cellulare"] as? String!)!)!)" contattiFut6.stringValue = contattiCliente6 if(((Stanza6Dic["accettata"] as? String!)!)! == "0") { self.accetta6.isHidden = false } else { self.accetta6.isHidden = true } avanti6.isHidden = true indietro6.isHidden = true } else { if (total6 > (currentIndex6+1) && currentIndex6 != 0) { avanti6.isHidden = false indietro6.isHidden = false elimina6.isHidden = false let Stanza6Dic: NSDictionary = data_array6[currentIndex6] as! NSDictionary prenID6.stringValue = (Stanza6Dic["id_prenotazione"] as? String!)!; let stringaCliente6 = "\(((Stanza6Dic["nome"] as? String!)!)!) \(((Stanza6Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo6.stringValue = stringaCliente6 let dateFutu6 = "\(((Stanza6Dic["data_iniziale"] as? String!)!)!) - \(((Stanza6Dic["data_finale"] as? String!)!)!)" dataInizioFineFut6.stringValue = dateFutu6 let contattiCliente6 = "\(((Stanza6Dic["email"] as? String!)!)!) ≈ \(((Stanza6Dic["cellulare"] as? String!)!)!)" contattiFut6.stringValue = contattiCliente6 if(((Stanza6Dic["accettata"] as? String!)!)! == "0") { self.accetta6.isHidden = false } else { self.accetta6.isHidden = true } } else { if(currentIndex6 == 0) { avanti6.isHidden = false indietro6.isHidden = true elimina6.isHidden = false let Stanza6Dic: NSDictionary = data_array6[currentIndex6] as! NSDictionary prenID6.stringValue = (Stanza6Dic["id_prenotazione"] as? String!)!; let stringaCliente6 = "\(((Stanza6Dic["nome"] as? String!)!)!) \(((Stanza6Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo6.stringValue = stringaCliente6 let dateFutu6 = "\(((Stanza6Dic["data_iniziale"] as? String!)!)!) - \(((Stanza6Dic["data_finale"] as? String!)!)!)" dataInizioFineFut6.stringValue = dateFutu6 let contattiCliente6 = "\(((Stanza6Dic["email"] as? String!)!)!) ≈ \(((Stanza6Dic["cellulare"] as? String!)!)!)" contattiFut6.stringValue = contattiCliente6 if(((Stanza6Dic["accettata"] as? String!)!)! == "0") { self.accetta6.isHidden = false } else { self.accetta6.isHidden = true } } else { if (total6 == (currentIndex6+1)) { avanti6.isHidden = true indietro6.isHidden = false elimina6.isHidden = false let Stanza6Dic: NSDictionary = data_array6[currentIndex6] as! NSDictionary prenID6.stringValue = (Stanza6Dic["id_prenotazione"] as? String!)!; let stringaCliente6 = "\(((Stanza6Dic["nome"] as? String!)!)!) \(((Stanza6Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo6.stringValue = stringaCliente6 let dateFutu6 = "\(((Stanza6Dic["data_iniziale"] as? String!)!)!) - \(((Stanza6Dic["data_finale"] as? String!)!)!)" dataInizioFineFut6.stringValue = dateFutu6 let contattiCliente6 = "\(((Stanza6Dic["email"] as? String!)!)!) ≈ \(((Stanza6Dic["cellulare"] as? String!)!)!)" contattiFut6.stringValue = contattiCliente6 if(((Stanza6Dic["accettata"] as? String!)!)! == "0") { self.accetta6.isHidden = false } else { self.accetta6.isHidden = true } } } } } } } let when6 = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when6) { _ = self.checkFut6() } } @IBAction func indietro6Button(_ sender: Any) { currentIndex6 = currentIndex6 - 1 } @IBAction func avanti6Button(_ sender: Any) { currentIndex6 = currentIndex6 + 1 } @IBAction func accetta6Button(_ sender: Any) { let id_pren6 = prenID6.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=accettazione&stanza=6&id_pren=\(id_pren6)")!)) } @IBAction func elimina6Button(_ sender: Any) { let id_pren6 = prenID6.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=eliminazione&id_pren=\(id_pren6)")!)) } func checkFut7 () { myView13.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch2.php?idStanza=7")!)) let dataFut7 = data_request(forData: "stanza7.json") _ = json_parseData(dataFut7!) if let json7 = json_parseData(dataFut7!) { let data_array7: NSArray = (json7["data"] as? NSArray)! var total7 = 0 for _ in data_array7 { total7 = total7 + 1 } if total7 == 0 { prenID7.stringValue = "-"; nomeCognomeFutInfo7.stringValue = "Non ci sono prenotazioni"; dataInizioFineFut7.stringValue = "-" contattiFut7.stringValue = "-" avanti7.isHidden = true accetta7.isHidden = true elimina7.isHidden = true indietro7.isHidden = true } else { if total7 == 1 { elimina7.isHidden = false let Stanza7Dic: NSDictionary = data_array7[0] as! NSDictionary prenID7.stringValue = (Stanza7Dic["id_prenotazione"] as? String!)!; let stringaCliente7 = "\(((Stanza7Dic["nome"] as? String!)!)!) \(((Stanza7Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo7.stringValue = stringaCliente7 let dateFutu7 = "\(((Stanza7Dic["data_iniziale"] as? String!)!)!) - \(((Stanza7Dic["data_finale"] as? String!)!)!)" dataInizioFineFut7.stringValue = dateFutu7 let contattiCliente7 = "\(((Stanza7Dic["email"] as? String!)!)!) ≈ \(((Stanza7Dic["cellulare"] as? String!)!)!)" contattiFut7.stringValue = contattiCliente7 if(((Stanza7Dic["accettata"] as? String!)!)! == "0") { self.accetta7.isHidden = false } else { self.accetta7.isHidden = true } avanti7.isHidden = true indietro7.isHidden = true } else { if (total7 > (currentIndex7+1) && currentIndex7 != 0) { avanti7.isHidden = false indietro7.isHidden = false elimina7.isHidden = false let Stanza7Dic: NSDictionary = data_array7[currentIndex7] as! NSDictionary prenID7.stringValue = (Stanza7Dic["id_prenotazione"] as? String!)!; let stringaCliente7 = "\(((Stanza7Dic["nome"] as? String!)!)!) \(((Stanza7Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo7.stringValue = stringaCliente7 let dateFutu7 = "\(((Stanza7Dic["data_iniziale"] as? String!)!)!) - \(((Stanza7Dic["data_finale"] as? String!)!)!)" dataInizioFineFut7.stringValue = dateFutu7 let contattiCliente7 = "\(((Stanza7Dic["email"] as? String!)!)!) ≈ \(((Stanza7Dic["cellulare"] as? String!)!)!)" contattiFut7.stringValue = contattiCliente7 if(((Stanza7Dic["accettata"] as? String!)!)! == "0") { self.accetta7.isHidden = false } else { self.accetta7.isHidden = true } } else { if(currentIndex7 == 0) { avanti7.isHidden = false indietro7.isHidden = true elimina7.isHidden = false let Stanza7Dic: NSDictionary = data_array7[currentIndex7] as! NSDictionary prenID7.stringValue = (Stanza7Dic["id_prenotazione"] as? String!)!; let stringaCliente7 = "\(((Stanza7Dic["nome"] as? String!)!)!) \(((Stanza7Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo7.stringValue = stringaCliente7 let dateFutu7 = "\(((Stanza7Dic["data_iniziale"] as? String!)!)!) - \(((Stanza7Dic["data_finale"] as? String!)!)!)" dataInizioFineFut7.stringValue = dateFutu7 let contattiCliente7 = "\(((Stanza7Dic["email"] as? String!)!)!) ≈ \(((Stanza7Dic["cellulare"] as? String!)!)!)" contattiFut7.stringValue = contattiCliente7 if(((Stanza7Dic["accettata"] as? String!)!)! == "0") { self.accetta7.isHidden = false } else { self.accetta7.isHidden = true } } else { if (total7 == (currentIndex7+1)) { avanti7.isHidden = true indietro7.isHidden = false elimina7.isHidden = false let Stanza7Dic: NSDictionary = data_array7[currentIndex7] as! NSDictionary prenID7.stringValue = (Stanza7Dic["id_prenotazione"] as? String!)!; let stringaCliente7 = "\(((Stanza7Dic["nome"] as? String!)!)!) \(((Stanza7Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo7.stringValue = stringaCliente7 let dateFutu7 = "\(((Stanza7Dic["data_iniziale"] as? String!)!)!) - \(((Stanza7Dic["data_finale"] as? String!)!)!)" dataInizioFineFut7.stringValue = dateFutu7 let contattiCliente7 = "\(((Stanza7Dic["email"] as? String!)!)!) ≈ \(((Stanza7Dic["cellulare"] as? String!)!)!)" contattiFut7.stringValue = contattiCliente7 if(((Stanza7Dic["accettata"] as? String!)!)! == "0") { self.accetta7.isHidden = false } else { self.accetta7.isHidden = true } } } } } } } let when7 = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when7) { _ = self.checkFut7() } } @IBAction func indietro7Button(_ sender: Any) { currentIndex7 = currentIndex7 - 1 } @IBAction func avanti7Button(_ sender: Any) { currentIndex7 = currentIndex7 + 1 } @IBAction func accetta7Button(_ sender: Any) { let id_pren7 = prenID6.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=accettazione&stanza=7&id_pren=\(id_pren7)")!)) } @IBAction func elimina7Button(_ sender: Any) { let id_pren7 = prenID7.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=eliminazione&id_pren=\(id_pren7)")!)) } func checkFut8 () { myView14.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/fetch2.php?idStanza=8")!)) let dataFut8 = data_request(forData: "stanza8.json") _ = json_parseData(dataFut8!) if let json8 = json_parseData(dataFut8!) { let data_array8: NSArray = (json8["data"] as? NSArray)! var total8 = 0 for _ in data_array8 { total8 = total8 + 1 } if total8 == 0 { prenID8.stringValue = "-"; nomeCognomeFutInfo8.stringValue = "Non ci sono prenotazioni"; dataInizioFineFut8.stringValue = "-" contattiFut8.stringValue = "-" avanti8.isHidden = true accetta8.isHidden = true elimina8.isHidden = true indietro8.isHidden = true } else { if total8 == 1 { elimina8.isHidden = false let Stanza8Dic: NSDictionary = data_array8[0] as! NSDictionary prenID8.stringValue = (Stanza8Dic["id_prenotazione"] as? String!)!; let stringaCliente8 = "\(((Stanza8Dic["nome"] as? String!)!)!) \(((Stanza8Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo8.stringValue = stringaCliente8 let dateFutu8 = "\(((Stanza8Dic["data_iniziale"] as? String!)!)!) - \(((Stanza8Dic["data_finale"] as? String!)!)!)" dataInizioFineFut8.stringValue = dateFutu8 let contattiCliente8 = "\(((Stanza8Dic["email"] as? String!)!)!) ≈ \(((Stanza8Dic["cellulare"] as? String!)!)!)" contattiFut8.stringValue = contattiCliente8 if(((Stanza8Dic["accettata"] as? String!)!)! == "0") { self.accetta8.isHidden = false } else { self.accetta8.isHidden = true } avanti8.isHidden = true indietro8.isHidden = true } else { if (total8 > (currentIndex8+1) && currentIndex8 != 0) { avanti8.isHidden = false indietro8.isHidden = false elimina8.isHidden = false let Stanza8Dic: NSDictionary = data_array8[currentIndex8] as! NSDictionary prenID8.stringValue = (Stanza8Dic["id_prenotazione"] as? String!)!; let stringaCliente8 = "\(((Stanza8Dic["nome"] as? String!)!)!) \(((Stanza8Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo8.stringValue = stringaCliente8 let dateFutu8 = "\(((Stanza8Dic["data_iniziale"] as? String!)!)!) - \(((Stanza8Dic["data_finale"] as? String!)!)!)" dataInizioFineFut8.stringValue = dateFutu8 let contattiCliente8 = "\(((Stanza8Dic["email"] as? String!)!)!) ≈ \(((Stanza8Dic["cellulare"] as? String!)!)!)" contattiFut8.stringValue = contattiCliente8 if(((Stanza8Dic["accettata"] as? String!)!)! == "0") { self.accetta8.isHidden = false } else { self.accetta8.isHidden = true } } else { if(currentIndex8 == 0) { avanti8.isHidden = false indietro8.isHidden = true elimina8.isHidden = false let Stanza8Dic: NSDictionary = data_array8[currentIndex8] as! NSDictionary prenID8.stringValue = (Stanza8Dic["id_prenotazione"] as? String!)!; let stringaCliente8 = "\(((Stanza8Dic["nome"] as? String!)!)!) \(((Stanza8Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo8.stringValue = stringaCliente8 let dateFutu8 = "\(((Stanza8Dic["data_iniziale"] as? String!)!)!) - \(((Stanza8Dic["data_finale"] as? String!)!)!)" dataInizioFineFut8.stringValue = dateFutu8 let contattiCliente8 = "\(((Stanza8Dic["email"] as? String!)!)!) ≈ \(((Stanza8Dic["cellulare"] as? String!)!)!)" contattiFut8.stringValue = contattiCliente8 if(((Stanza8Dic["accettata"] as? String!)!)! == "0") { self.accetta8.isHidden = false } else { self.accetta8.isHidden = true } } else { if (total8 == (currentIndex8+1)) { avanti8.isHidden = true indietro8.isHidden = false elimina8.isHidden = false let Stanza8Dic: NSDictionary = data_array8[currentIndex8] as! NSDictionary prenID8.stringValue = (Stanza8Dic["id_prenotazione"] as? String!)!; let stringaCliente8 = "\(((Stanza8Dic["nome"] as? String!)!)!) \(((Stanza8Dic["cognome"] as? String!)!)!)" nomeCognomeFutInfo8.stringValue = stringaCliente8 let dateFutu8 = "\(((Stanza8Dic["data_iniziale"] as? String!)!)!) - \(((Stanza8Dic["data_finale"] as? String!)!)!)" dataInizioFineFut8.stringValue = dateFutu8 let contattiCliente8 = "\(((Stanza8Dic["email"] as? String!)!)!) ≈ \(((Stanza8Dic["cellulare"] as? String!)!)!)" contattiFut8.stringValue = contattiCliente8 if(((Stanza8Dic["accettata"] as? String!)!)! == "0") { self.accetta8.isHidden = false } else { self.accetta8.isHidden = true } } } } } } } let when8 = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when8) { _ = self.checkFut8() } } @IBAction func indietro8Button(_ sender: Any) { currentIndex8 = currentIndex8 - 1 } @IBAction func avanti8Button(_ sender: Any) { currentIndex8 = currentIndex8 + 1 } @IBAction func accetta8Button(_ sender: Any) { let id_pren8 = prenID8.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=accettazione&stanza=8&id_pren=\(id_pren8)")!)) } @IBAction func elimina8Button(_ sender: Any) { let id_pren8 = prenID8.stringValue self.myView7.mainFrame.load(URLRequest(url: URL(string: "http://127.0.0.1/kds/api/edit.php?source=eliminazione&id_pren=\(id_pren8)")!)) } @IBAction func showBox5(_ sender: Any) { self.box5.isHidden = false } }
gpl-3.0
6c160f7e2adf90f3c23948c09194bc8a
40.979405
391
0.446925
4.618192
false
false
false
false
frootloops/swift
test/SILGen/super_init_refcounting.swift
1
4337
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Foo { init() {} init(_ x: Foo) {} init(_ x: Int) {} } class Bar: Foo { // CHECK-LABEL: sil hidden @_T022super_init_refcounting3BarC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[INPUT_SELF:%.*]] : $Bar): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Bar } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[INPUT_SELF]] to [init] [[PB_SELF_BOX]] // CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[ORIG_SELF_UP:%.*]] = upcast [[ORIG_SELF]] // CHECK-NOT: copy_value [[ORIG_SELF_UP]] // CHECK: [[SUPER_INIT:%[0-9]+]] = function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF_UP]]) // CHECK: [[NEW_SELF_DOWN:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[NEW_SELF_DOWN]] to [init] [[PB_SELF_BOX]] override init() { super.init() } } extension Foo { // CHECK-LABEL: sil hidden @_T022super_init_refcounting3FooC{{[_0-9a-zA-Z]*}}fc // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Foo } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[SUPER_INIT:%.*]] = class_method // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF]]) // CHECK: store [[NEW_SELF]] to [init] [[PB_SELF_BOX]] convenience init(x: Int) { self.init() } } class Zim: Foo { var foo = Foo() // CHECK-LABEL: sil hidden @_T022super_init_refcounting3ZimC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo } class Zang: Foo { var foo: Foo override init() { foo = Foo() super.init() } // CHECK-LABEL: sil hidden @_T022super_init_refcounting4ZangC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @_T022super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo } class Bad: Foo { // Invalid code, but it's not diagnosed till DI. We at least shouldn't // crash on it. override init() { super.init(self) } } class Good: Foo { let x: Int // CHECK-LABEL: sil hidden @_T022super_init_refcounting4GoodC{{[_0-9a-zA-Z]*}}fc // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Good } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store %0 to [init] [[PB_SELF_BOX]] // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[PB_SELF_BOX]] // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X_ADDR]] : $*Int // CHECK: assign {{.*}} to [[WRITE]] : $*Int // CHECK: [[SELF_OBJ:%.*]] = load [take] [[PB_SELF_BOX]] : $*Good // CHECK: [[SUPER_OBJ:%.*]] = upcast [[SELF_OBJ]] : $Good to $Foo // CHECK: [[BORROWED_SUPER:%.*]] = begin_borrow [[SUPER_OBJ]] // CHECK: [[DOWNCAST_BORROWED_SUPER:%.*]] = unchecked_ref_cast [[BORROWED_SUPER]] : $Foo to $Good // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[DOWNCAST_BORROWED_SUPER]] : $Good, #Good.x // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[X_ADDR]] : $*Int // CHECK: [[X:%.*]] = load [trivial] [[READ]] : $*Int // CHECK: end_borrow [[BORROWED_SUPER]] from [[SUPER_OBJ]] // CHECK: [[SUPER_INIT:%.*]] = function_ref @_T022super_init_refcounting3FooCACSicfc : $@convention(method) (Int, @owned Foo) -> @owned Foo // CHECK: apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]]) override init() { x = 10 super.init(x) } }
apache-2.0
c961915e015079f4b72ae7e4d37b89e0
42.808081
149
0.541849
3.231744
false
false
false
false
StachkaConf/ios-app
StachkaIOS/StachkaIOS/Classes/User Stories/Favourites/Feed/Assembly/FavouritesFeedAssembly.swift
1
879
// // FavouritesFeedAssembly.swift // StachkaIOS // // Created by Konstantin Mordan on 02/04/2017. // Copyright © 2017 m.rakhmanov. All rights reserved. // import Foundation import UIKit class FavouritesFeedAssembly: ModuleAssembly { let assemblyFactory: AssemblyFactory init(assemblyFactory: AssemblyFactory) { self.assemblyFactory = assemblyFactory } func module() -> UIViewController { let viewController: FeedViewController = UIStoryboard.createControllerFromStoryboardWith(name: StoryboardName.talks) let viewModel = FavouritesFeedViewModelImplementation(view: viewController) viewController.viewModel = viewModel // FIXME: это заглушка, чтобы проверить работу табов viewController.view.backgroundColor = UIColor.red return viewController } }
mit
e39c0bb492ead6539e0c5e009e69fa10
28.034483
124
0.729216
4.811429
false
false
false
false
arnaudbenard/my-npm
Pods/Charts/Charts/Classes/Renderers/RadarChartRenderer.swift
20
9888
// // RadarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class RadarChartRenderer: ChartDataRendererBase { internal weak var _chart: RadarChartView! public init(chart: RadarChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) _chart = chart } public override func drawData(#context: CGContext) { if (_chart !== nil) { var radarData = _chart.data if (radarData != nil) { for set in radarData!.dataSets as! [RadarChartDataSet] { if (set.isVisible) { drawDataSet(context: context, dataSet: set) } } } } } internal func drawDataSet(#context: CGContext, dataSet: RadarChartDataSet) { CGContextSaveGState(context) var sliceangle = _chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels var factor = _chart.factor var center = _chart.centerOffsets var entries = dataSet.yVals var path = CGPathCreateMutable() var hasMovedToPoint = false for (var j = 0; j < entries.count; j++) { var e = entries[j] var p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value - _chart.chartYMin) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle) if (p.x.isNaN) { continue } if (!hasMovedToPoint) { CGPathMoveToPoint(path, nil, p.x, p.y) hasMovedToPoint = true } else { CGPathAddLineToPoint(path, nil, p.x, p.y) } } CGPathCloseSubpath(path) // draw filled if (dataSet.isDrawFilledEnabled) { CGContextSetFillColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextSetAlpha(context, dataSet.fillAlpha) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextFillPath(context) } // draw the line (only if filled is disabled or alpha is below 255) if (!dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextSetLineWidth(context, dataSet.lineWidth) CGContextSetAlpha(context, 1.0) CGContextBeginPath(context) CGContextAddPath(context, path) CGContextStrokePath(context) } CGContextRestoreGState(context) } public override func drawValues(#context: CGContext) { if (_chart.data === nil) { return } var data = _chart.data! var defaultValueFormatter = _chart.valueFormatter var sliceangle = _chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels var factor = _chart.factor var center = _chart.centerOffsets var yoffset = CGFloat(5.0) for (var i = 0, count = data.dataSetCount; i < count; i++) { var dataSet = data.getDataSetByIndex(i) as! RadarChartDataSet if (!dataSet.isDrawValuesEnabled) { continue } var entries = dataSet.yVals for (var j = 0; j < entries.count; j++) { var e = entries[j] var p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle) var valueFont = dataSet.valueFont var valueTextColor = dataSet.valueTextColor var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(e.value)!, point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } public override func drawExtras(#context: CGContext) { drawWeb(context: context) } private var _webLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawWeb(#context: CGContext) { var sliceangle = _chart.sliceAngle CGContextSaveGState(context) // calculate the factor that is needed for transforming the value to // pixels var factor = _chart.factor var rotationangle = _chart.rotationAngle var center = _chart.centerOffsets // draw the web lines that come from the center CGContextSetLineWidth(context, _chart.webLineWidth) CGContextSetStrokeColorWithColor(context, _chart.webColor.CGColor) CGContextSetAlpha(context, _chart.webAlpha) for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++) { var p = ChartUtils.getPosition(center: center, dist: CGFloat(_chart.yRange) * factor, angle: sliceangle * CGFloat(i) + rotationangle) _webLineSegmentsBuffer[0].x = center.x _webLineSegmentsBuffer[0].y = center.y _webLineSegmentsBuffer[1].x = p.x _webLineSegmentsBuffer[1].y = p.y CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2) } // draw the inner-web CGContextSetLineWidth(context, _chart.innerWebLineWidth) CGContextSetStrokeColorWithColor(context, _chart.innerWebColor.CGColor) CGContextSetAlpha(context, _chart.webAlpha) var labelCount = _chart.yAxis.entryCount for (var j = 0; j < labelCount; j++) { for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++) { var r = CGFloat(_chart.yAxis.entries[j] - _chart.chartYMin) * factor var p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle) var p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle) _webLineSegmentsBuffer[0].x = p1.x _webLineSegmentsBuffer[0].y = p1.y _webLineSegmentsBuffer[1].x = p2.x _webLineSegmentsBuffer[1].y = p2.y CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } private var _lineSegments = [CGPoint](count: 4, repeatedValue: CGPoint()) public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { if (_chart.data === nil) { return } var data = _chart.data as! RadarChartData CGContextSaveGState(context) CGContextSetLineWidth(context, data.highlightLineWidth) if (data.highlightLineDashLengths != nil) { CGContextSetLineDash(context, data.highlightLineDashPhase, data.highlightLineDashLengths!, data.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } var sliceangle = _chart.sliceAngle var factor = _chart.factor var center = _chart.centerOffsets for (var i = 0; i < indices.count; i++) { var set = _chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as! RadarChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) // get the index to highlight var xIndex = indices[i].xIndex var e = set.entryForXIndex(xIndex) if (e === nil || e!.xIndex != xIndex) { continue } var j = set.entryIndex(entry: e!, isEqual: true) var y = (e!.value - _chart.chartYMin) if (y.isNaN) { continue } var p = ChartUtils.getPosition(center: center, dist: CGFloat(y) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle) _lineSegments[0] = CGPoint(x: p.x, y: 0.0) _lineSegments[1] = CGPoint(x: p.x, y: viewPortHandler.chartHeight) _lineSegments[2] = CGPoint(x: 0.0, y: p.y) _lineSegments[3] = CGPoint(x: viewPortHandler.chartWidth, y: p.y) CGContextStrokeLineSegments(context, _lineSegments, 4) } CGContextRestoreGState(context) } }
mit
b0d9f72ecb06e7c2b0ca46d369a13b66
32.522034
273
0.545914
5.327586
false
false
false
false