repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dche/FlatUtil
Sources/Observable.swift
1
93429
// // FlatUtil - Observalbe.swift // // A simple implementation of ReactiveX. // // Copyright (c) 2017 The FlatUtil authors. // Licensed under MIT License. // Operators that are not implemented: // - And/Then/When. Complex. // - Join. Name is too general while the meaning is obscure. // - Materialize/Dematerialize. Less useful. // - Serialize. Not needed. // - Using. Swift does not need it. // - Connectable Observable Operators. Vague concept. // - Backpressure. TBI. // - To. Should not be an operator in Swift. // import Dispatch /// The default dispatch queue for executing generators of `Observable`s. /// This is a concurrent queue. public let emittingQueue = DispatchQueue( label: "com.eleuth.FlatUtil.Observable.emittingQueue", qos: .background, attributes: .concurrent ) // Used when serialization is necessary. private let serialQueue = DispatchQueue( label: "com.eleuth.FlatUtil.Observable.serialQueue", qos: .background ) // The dispatch queue for synchronizing critical region access in `Subject`. private let subjectSyncQueue = DispatchQueue( label: "com.eleuth.FlatUtil.Observable.subjectSyncQueue", qos: .background ) // A simple circular buffer. // // NOTE: Not thread-safe. private struct CircularQueue<Item> { private var _head = 0 private var _tail = 0 private var _buffer: [EmittingResult<Item>] private let capacityFixed: Bool init (capacity: Int, fixed: Bool = true) { assert(capacity > 0) self._buffer = [EmittingResult<Item>]( repeating: .complete, // 1 for separating space. count: capacity + 1 ) self.capacityFixed = fixed } var iterator: AnyIterator<EmittingResult<Item>> { var p = _head return AnyIterator { () -> EmittingResult<Item>? in guard p != self._tail else { return nil } let item = self._buffer[p] p = (p + 1) % self._buffer.capacity return item } } var count: Int { if _head == _tail { return 0 } if _head < _tail { return _tail - _head } return _buffer.capacity - _head + _tail } var isEmpty: Bool { return _head == _tail } var isFull: Bool { return count == _buffer.capacity - 1 } var head: EmittingResult<Item>? { guard !isEmpty else { return nil } return _buffer[_head] } var last: EmittingResult<Item>? { guard !isEmpty else { return nil } let cap = _buffer.capacity return _buffer[(_tail + cap - 1) % cap] } mutating func push(item: EmittingResult<Item>) { let cap = _buffer.capacity if capacityFixed || count < cap - 1 { _buffer[_tail] = item _tail = (_tail + 1) % cap // Release value. _buffer[_tail] = .complete if (_head == _tail) { _head = (_head + 1) % cap } } else { var cq = CircularQueue(capacity: (cap - 1) * 2 + 1) for i in self.iterator { cq.push(item: i) } cq.push(item: item) self = cq } } mutating func pop() -> EmittingResult<Item>? { guard !isEmpty else { return nil } let h = _buffer[_head] // Release value. _buffer[_head] = .complete _head = (_head + 1) % _buffer.capacity return h } } /// Standard `Observer` protocol. public protocol ObserverProtocol { associatedtype Item func onNext(_ item: Item) func onComplete() func onError(_ error: Error) } /// A general implementation of `ObserverProtocol`. public struct Observer<T>: ObserverProtocol { public typealias Item = T private let next: (Item) -> Void private let complete: () -> Void private let error: (Error) -> Void /// Creates an `Observer` with given callbacks. /// /// - parameters: /// - complete: Called within `onComplete`. /// - error: Called within `onError`. /// - next: Called within `onNext`. public init ( complete: @escaping () -> Void = { }, error: @escaping (Error) -> Void = { _ in }, next: @escaping (Item) -> Void ) { self.next = next self.complete = complete self.error = error } public func onNext(_ item: Item) { self.next(item) } public func onComplete() { self.complete() } public func onError(_ error: Error) { self.error(error) } } /// Emitting result of observables. public enum EmittingResult<T> { case item(T) case error(Error) case complete /// Returns `true` if the receiver is a termination notification. public var isTermination: Bool { switch self { case .item(_): return false default: return true } } /// Returns the item or `nil` if the receiver is termination. public var item: T? { switch self { case let .item(itm): return itm default: return nil } } } extension EmittingResult where T: Equatable { // SWIFT EVOLUTION: extension EmittingResult: Equatable where T: Equatable {} public static func == (lhs: EmittingResult<T>, rhs: EmittingResult<T>) -> Bool { switch (lhs, rhs) { case let (.item(li), .item(ri)) where li == ri: return true case (.complete, .complete): return true default: return false } } } public final class Subscription<I> { public typealias Item = I private var _cancelled = false private let _epoch: Time fileprivate init<S: ObservableProtocol, T: ObserverProtocol> ( on queue: DispatchQueue = emittingQueue, observable: S, observer: T ) where S.Item == Item, T.Item == Item { _epoch = Time.now observable.subscribe(at: _epoch, on: queue) { er in if self._cancelled { return false } switch er { case let .item(itm): observer.onNext(itm) return !self._cancelled case .complete: observer.onComplete() case let .error(e): observer.onError(e) } return false } } public func unsubscribe() { self._cancelled = true } } /// Base _Observable_ type. public protocol ObservableProtocol { /// Type of item to be emitted. associatedtype Item /// This method defines the protocol between an _observable_ and its /// users, which can be either _oberver_s or other _observable_s. /// /// - parameters: /// - time: When the subscription is created. /// - queue: The dispatch queue in which the `callback` should be /// executed. /// - callback: User provided callback function. If this function /// returns `false`, the receiver shall stop emitting anything, /// including termianting notifications. func subscribe( at time: Time, on queue: DispatchQueue, callback: @escaping (EmittingResult<Item>) -> Bool ) } extension ObservableProtocol { public func subscribe<O: ObserverProtocol>( on queue: DispatchQueue = emittingQueue, observer o: O ) -> Subscription<Item> where O.Item == Item { return Subscription(on: queue, observable: self, observer: o) } public func subscribe( on queue: DispatchQueue = emittingQueue, complete: @escaping () -> Void = { }, error: @escaping (Error) -> Void = { _ in }, next: @escaping (Item) -> Void ) -> Subscription<Item> { let o = Observer<Item>(complete: complete, error: error, next: next) return Subscription(on: queue, observable: self, observer: o) } } /// A general implementation of `ObservableProtocol` based on a generator /// function. public struct Observable<I>: ObservableProtocol { public typealias Item = I private let gen: (Time, DispatchQueue, @escaping (EmittingResult<I>) -> Bool) -> Void /// Creates an `Observable` by providing a generator function. /// /// - parameter generator: The generator function. Obviously it is /// used to impelent the `subscribe(at:on:callback:)` method. /// /// - seealso: [`Defer` operator documentation] /// (http://reactivex.io/documentation/operators/defer.html) on ReactiveX. public init (generator: @escaping (Time, DispatchQueue, @escaping (EmittingResult<Item>) -> Bool) -> Void) { self.gen = generator } /// Creates an `Observable` which emits items by directly using the /// observer interface. /// /// - note: This is the only way to create an ill-behaved observable. /// /// - seealso: [`Create` operator documentation] /// (http://reactivex.io/documentation/operators/create.html) on ReactiveX. public init(callback: @escaping (Observer<Item>) -> Void) { self.gen = { _, _, cb in var isCancelled = false let o = Observer<Item>(complete: { guard !isCancelled else { return } isCancelled = !cb(.complete) }, error: { guard !isCancelled else { return } isCancelled = !cb(.error($0)) }, next: { guard !isCancelled else { return } isCancelled = !cb(.item($0)) }) callback(o) } } public func subscribe( at time: Time, on queue: DispatchQueue, callback: @escaping (EmittingResult<Item> ) -> Bool) { queue.async { self.gen(time, queue, callback) } } } // MARK: Subject /// Generic `Subject` type. /// /// - seealso: [Subject documentation on ReactiveX] /// (http://reactivex.io/documentation/subject.html) on ReactiveX.. public protocol Subject: ObservableProtocol, ObserverProtocol {} // This class is used for: // 1. Sharing implementations, // 2. Breaking the cycle of type dependencies. private final class SubjectImpl<Item> { typealias Callback = (EmittingResult<Item>) -> Void private var _nextHandle: Int = 0 private var _callbacks: [Int:Callback] = [:] var nextHandle: Int { self._nextHandle += 1 return self._nextHandle } func emit(item: EmittingResult<Item>) { for cb in _callbacks.values { cb(item) } } // Returns the handle of registration. func register(handle: Int, callback: @escaping Callback) { assert(handle == self._nextHandle) assert(_callbacks[handle] == nil) _callbacks[handle] = callback } func emit(item: EmittingResult<Item>, to handle: Int, on queue: DispatchQueue) -> Bool { guard let cb = _callbacks[handle] else { return false } queue.async { cb(item) } return true } // Triggered when an `Observer` cancelled subscription. func unregister(handle: Int) { subjectSyncQueue.sync { assert(handle > 0) assert(self._callbacks[handle] != nil) self._callbacks.removeValue(forKey: handle) } } } /// An `AsyncSubject` emits the last value (and only the last value) emitted /// by the source observable, and only after that source observable completes. /// /// - seealso: [Subject documentation] /// (http://reactivex.io/documentation/subject.html) on ReactiveX. public final class AsyncSubject<I>: Subject { public typealias Item = I private var _last: EmittingResult<Item>? = nil private var _impl: SubjectImpl<Item>? public init () { self._impl = SubjectImpl<Item>() } public func subscribe( at time: Time, on queue: DispatchQueue, callback: @escaping (EmittingResult<Item>) -> Bool ) { subjectSyncQueue.async { guard let impl = self._impl else { assert(self._last != nil) let last = self._last! queue.async { switch last { case .item(_): let _ = callback(last) && callback(.complete) default: let _ = callback(last) } } return } let h = impl.nextHandle impl.register(handle: h) { er in queue.async { switch er { case .item(_): let _ = callback(er) && callback(.complete) default: let _ = callback(er) } // Unregister is unnecessary. } } } } public func onNext(_ item: Item) { subjectSyncQueue.async { guard self._impl != nil else { return } self._last = .item(item) } } public func onComplete() { subjectSyncQueue.async { guard let impl = self._impl else { return } // No items at all. guard let last = self._last else { impl.emit(item: .complete) self._impl = nil self._last = .complete return } switch last { case .item(_): impl.emit(item: last) self._impl = nil default: fatalError("Unreachable.") } } } public func onError(_ error: Error) { subjectSyncQueue.async { guard let impl = self._impl else { return } impl.emit(item: .error(error)) self._impl = nil self._last = .error(error) } } } /// `BehaviorSubject` emits the most recent item emitted by /// the source, or a default item if none has yet been emitted. /// /// - seealso: [Subject documentation] /// (http://reactivex.io/documentation/subject.html) on ReactiveX. public final class BehaviorSubject<I>: Subject { public typealias Item = I private var _current: EmittingResult<Item> private var _impl: SubjectImpl<Item>? /// Returns the latest item of the receiver. public var latestItem: Item? { return _current.item } public init (initial: Item) { self._current = .item(initial) self._impl = SubjectImpl<Item>() } public func subscribe( at time: Time, on queue: DispatchQueue, callback: @escaping (EmittingResult<Item>) -> Bool ) { subjectSyncQueue.async { switch self._current { case .item(_): guard let impl = self._impl else { queue.async { let _ = callback(self._current) && callback(.complete) } return } let h = impl.nextHandle impl.register(handle: h) { er in queue.async { switch er { case .item(_): if !callback(er) { impl.unregister(handle: h) } default: let _ = callback(er) } } } let _ = impl.emit(item: self._current, to: h, on: queue) case .complete: fatalError("Unreachable.") case .error(_): queue.async { let _ = callback(self._current) } } } } public func onNext(_ item: Item) { subjectSyncQueue.async { guard let impl = self._impl else { return } self._current = .item(item) impl.emit(item: self._current) } } public func onComplete() { subjectSyncQueue.async { guard let impl = self._impl else { return } self._impl = nil impl.emit(item: .complete) } } public func onError(_ error: Error) { subjectSyncQueue.async { guard let impl = self._impl else { return } self._impl = nil self._current = .error(error) impl.emit(item: self._current) } } } /// `PublishSubject` emits only those items that are emitted by the source /// observable subsequent to the time of the subscription. /// /// - seealso: [Subject documentation] /// (http://reactivex.io/documentation/subject.html) on ReactiveX. public final class PublishSubject<I>: Subject { public typealias Item = I private var _termination: EmittingResult<Item>? = nil private var _impl: SubjectImpl<Item>? public init () { self._impl = SubjectImpl<Item>() } public func subscribe( at time: Time, on queue: DispatchQueue, callback: @escaping (EmittingResult<Item>) -> Bool ) { subjectSyncQueue.async { guard let impl = self._impl else { assert(self._termination != nil) let term = self._termination! assert(term.isTermination) queue.async { let _ = callback(term) } return } let h = impl.nextHandle impl.register(handle: h) { er in queue.async { switch er { case .item(_): if !callback(er) { impl.unregister(handle: h) } default: let _ = callback(er) } } } } } public func onNext(_ item: Item) { subjectSyncQueue.async { guard let impl = self._impl else { return } assert(self._termination == nil) impl.emit(item: .item(item)) } } public func onComplete() { subjectSyncQueue.async { guard let impl = self._impl else { return } self._impl = nil self._termination = .complete impl.emit(item: .complete) } } public func onError(_ error: Error) { subjectSyncQueue.async { guard let impl = self._impl else { return } self._impl = nil self._termination = .error(error) impl.emit(item: self._termination!) } } } /// `ReplaySubject` emits to any observer all of the items it receives, /// regardless of when the observer subscribes. /// /// - note: `ReplaySubject` does not record the time intervals between items. /// /// - seealso: [Subject documentation] /// (http://reactivex.io/documentation/subject.html) on ReactiveX. public final class ReplaySubject<I>: Subject { public typealias Item = I private var _records: CircularQueue<Item> private var _impl: SubjectImpl<Item>? public init (capacity: Int) { self._records = CircularQueue<Item>(capacity: Swift.max(capacity + 1, 2)) self._impl = SubjectImpl<Item>() } public func subscribe( at time: Time, on queue: DispatchQueue, callback: @escaping (EmittingResult<Item>) -> Bool ) { subjectSyncQueue.async { guard let impl = self._impl else { queue.async { for item in self._records.iterator { var cancelled = false switch item { case .item(_): cancelled = !callback(item) default: let _ = callback(item) cancelled = true } if cancelled { break } } } return } let h = impl.nextHandle impl.register(handle: h) { er in queue.async { switch er { case .item(_): if !callback(er) { impl.unregister(handle: h) } default: let _ = callback(er) } } } for item in self._records.iterator { guard impl.emit(item: item, to: h, on: queue) else { break } } } } public func onNext(_ item: Item) { subjectSyncQueue.async { guard let impl = self._impl else { return } let e: EmittingResult<Item> = .item(item) impl.emit(item: e) self._records.push(item: e) } } public func onComplete() { subjectSyncQueue.async { guard let impl = self._impl else { return } self._records.push(item: .complete) self._impl = nil impl.emit(item: .complete) } } public func onError(_ error: Error) { subjectSyncQueue.async { guard let impl = self._impl else { return } let e: EmittingResult<Item> = .error(error) self._records.push(item: e) self._impl = nil impl.emit(item: e) } } } // MARK: Creating extension Observable { /// Creates an `Observale` that emits items produced by a generator /// function. /// /// - example: /// /// ```swift /// Observable.generate( /// first: 1, /// until: { $0 > 100 } /// next: { $0 + 1 } /// ) /// ``` public static func generate( first: Item, until: @escaping (Item) -> Bool, next: @escaping (Item) throws -> Item ) -> Observable<Item> { return Observable<Item>.init() { _, _, cb in var pi = first if until(pi) { let _ = cb(.complete) return } while cb(.item(pi)) { do { pi = try next(pi) } catch { let _ = cb(.error(error)) break } if until(pi) { let _ = cb(.complete) break } } } } /// Creates an `Observable` that emits no items but terminates normally. /// /// - seealso: [`Empty` operator documentation] /// (http://reactivex.io/documentation/operators/empty-never-throw.html) on ReactiveX. public static func empty() -> Observable<Item> { return Observable<Item>() { _, _, cb in let _ = cb(.complete) } } /// Creates an `Observable` that emits no items and terminates with an /// error. /// /// - seealso: [`Throw` operator documentation] /// (http://reactivex.io/documentation/operators/empty-never-throw.html) on ReactiveX. public static func error(_ err: Error) -> Observable<Item> { return Observable<Item>() { _, _, cb in let _ = cb(.error(err)) } } /// Creates an `Observable` from a `Sequence`. /// /// - seealso: [`From` operator documentation] /// (http://reactivex.io/documentation/operators/from.html) on ReactiveX. public static func from<S: Sequence>(sequence: S) -> Observable<Item> where S.Iterator.Element == Item { return Observable<Item>() { _, _, cb in var iter = sequence.makeIterator() while let itm = iter.next() { guard cb(.item(itm)) else { return } } let _ = cb(.complete) } } /// Creates an `Observable` that only emits the given item and then /// completes. /// /// - seealso: [`Just` operator documentation] /// (http://reactivex.io/documentation/operators/just.html) on ReactiveX. public static func just(_ item: Item) -> Observable<Item> { return Observable<Item>() { _, _, cb in let _ = cb(.item(item)) && cb(.complete) } } /// Creates an `Observable` that does not emit anything. /// /// - seealso: [`Never` operator documentation] /// (http://reactivex.io/documentation/operators/empty-never-throw.html) on ReactiveX. public static func never() -> Observable<Item> { return Observable<Item>() { _, _, _ in } } /// Creates an `Observable` that emits given item repeatedly. /// /// - seealso: [`Repeat` operator documentation] /// (http://reactivex.io/documentation/operators/repeat.html) on ReactiveX. public static func `repeat`(_ item: Item, count: Int) -> Observable<Item> { return Observable<Item>() { _, _, cb in var i = 0 while i < count { guard cb(.item(item)) else { return } i += 1 } let _ = cb(.complete) } } /// Creates an `Observable` that emits the return value of given /// closure. /// /// - seealso: [`Start` operator documentation] /// (http://reactivex.io/documentation/operators/start.html) on ReactiveX. public static func start(_ operation: @autoclosure @escaping () -> Item) -> Observable<Item> { return Observable<Item>() { _, _, cb in let _ = cb(.item(operation())) && cb(.complete) } } /// Creates an `Observable` that emits given item at given time. /// If `at` is a past time, it emits nothing. /// /// - seealso: [`Timer` operator documentation] /// (http://reactivex.io/documentation/operators/timer.html) on ReactiveX. public static func timer(_ item: Item, at: Time) -> Observable<Item> { return Observable<Item>() { _, q, cb in guard Time.now < at else { let _ = cb(.complete) return } let ns = DispatchTime.now() + (at - Time.now).seconds q.asyncAfter(deadline: ns) { let _ = cb(.item(item)) && cb(.complete) } } } /// Creates an `Observable` that emits given item after a given delay. /// /// - seealso: [`Timer` operator documentation] /// (http://reactivex.io/documentation/operators/timer.html) on ReactiveX. public static func timer(_ item: Item, after: TimeInterval) -> Observable<Item> { return Observable<Item>() { t, q, cb in assert(t <= Time.now) let ns = DispatchTime.now() + (after - (Time.now - t)).seconds q.asyncAfter(deadline: ns) { let _ = cb(.item(item)) && cb(.complete) } } } } extension Observable where Item == Int { /// Creates an `Observable` that emits a sequence of intergers spaced /// by a given time interval. /// /// - seealso: [`Interval` operator documentation] /// (http://reactivex.io/documentation/operators/interval.html) on ReactiveX. public static func interval(_ ti: TimeInterval) -> Observable<Int> { return Observable<Int>() { t, q, cb in var i = 0 func schedule() { guard cb(.item(i)) else { return } i += 1 let et = ti * i let now = Time.now - t guard et > now else { q.async { schedule() } return } let after = et - now q.asyncAfter(deadline: DispatchTime.now() + after.seconds) { schedule() } } q.async { schedule() } } } /// Creates an `Observable` that emits a particular range of sequential /// integers. /// /// - seealso: [`Range` operator documentation] /// (http://reactivex.io/documentation/operators/range.html) on ReactiveX. public static func range(start: Int, count: Int) -> Observable<Int> { return Observable<Int>() { _, _, cb in var i = start while i < start + count { guard cb(.item(i)) else { return } i += 1 } let _ = cb(.complete) } } } // MARK: Transforming extension ObservableProtocol { /// Returns an `Observable` that forwards anything the receiver emits. public func mirror() -> Observable<Item> { return Observable<Item> { t, q, cb in self.subscribe(at: t, on: q, callback: { er in switch er { case .item(_): return cb(er) default: let _ = cb(er) } return false }) } } /// Returns an `Observable` that periodically gather items emitted by the /// receiver into bundles and emits these bundles rather than emitting the /// items one at a time. /// /// - seealso: [`Buffer` operator documentation] /// (http://reactivex.io/documentation/operators/buffer.html) on ReactiveX. public func buffer(count: Int) -> Observable<[Item]> { guard count > 0 else { return Observable<[Item]>.empty() } return Observable<[Item]>() { t, q, cb in var buf: [Item] = [] self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): buf.append(itm) guard buf.count < count else { let b = cb(.item(buf)) buf = [] return b } return true case let .error(e): let _ = cb(.error(e)) case .complete: if buf.count > 0 { let _ = cb(.item(buf)) && cb(.complete) buf = [] } else { let _ = cb(.complete) } } return false } } } /// Transform the items emitted by an observable into Observables, /// then flatten the emissions from those into a single Observable. /// /// - note: The result `Observable` is terminated when: /// 1. Error is emitted by either the receiver or any generated /// Observables. /// 2. The receiver and all generated observables complete. /// /// - seealso: ['FlatMap' operator documentation] /// (http://reactivex.io/documentation/operators/flatmap.html) on ReactiveX. public func flatMap<T>( _ operation: @escaping (Item) -> Observable<T> ) -> Observable<T> { return Observable<T>() { t, q, cb in var count = 1 var isTerminated = false let lcb = { (er: EmittingResult<T>) -> Bool in guard !isTerminated else { return false } switch er { case .item(_): q.async { isTerminated = !cb(er) } return true case .complete: count -= 1 if count == 0 { q.async { let _ = cb(.complete) } } case .error(_): q.async { let _ = cb(er) } isTerminated = true } return false } self.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: { er in guard !isTerminated else { return false } switch er { case let .item(itm): let o = operation(itm) count += 1 o.observe(on: emittingQueue).subscribe(at: t, on: serialQueue, callback: lcb) return true case .complete: count -= 1 if count == 0 { q.async { let _ = cb(.complete) } } case let .error(e): q.async { let _ = cb(.error(e)) } isTerminated = true } return false }) } } /// Transforms the emission of the receiver into `Observable`s, and returns /// an `Observable` that emits the items emitted by the latest one. /// /// - note: This operator is also called `SwitchMap`. /// /// - seealso: ['FlatMap' operator documentation] /// (http://reactivex.io/documentation/operators/flatmap.html) on ReactiveX. public func flatMapLatest<T>( _ operation: @escaping (Item) -> Observable<T> ) -> Observable<T> { return Observable<T> { t, q, cb in var i = -1 var count = 1 var isTerminated = false func subscribe(_ o: Observable<T>, tag: Int) { o.observe(on: emittingQueue).subscribe(at: Time.now, on: serialQueue) { er in guard i == tag else { return false } switch er { case .item(_): q.async { isTerminated = !cb(er) } return true case .complete: count -= 1 if count == 0 { q.async { let _ = cb(.complete) } } case .error(_): q.async { let _ = cb(er) } isTerminated = true } return false } } self.observe(on: emittingQueue).subscribe(at: t, on: serialQueue) { er in switch er { case let .item(o): i += 1 if count == 1 { count = 2 } let tag = i q.async { subscribe(operation(o), tag: tag) } return true case .complete: count -= 1 if count == 0 { q.async { let _ = cb(.complete) } } case let .error(e): q.async { let _ = cb(.error(e)) isTerminated = true } } return false } } } /// Returns an `Observable` that divides the emission of the receiver /// into a set of `Observable`s. The division is based on a selector /// function. /// /// - note: Cancellation of the receiver does not stop the emission of /// emitted `Observable`s. /// /// - note: Observables emitted by the result `Observable` are _hot_ /// even if the receiver is _cold_. See (Observalbe documentation) /// (http://reactivex.io/documentation/observable.html) on ReactiveX. /// /// - seealso: ['GroupBy' operator documentation] /// (http://reactivex.io/documentation/operators/groupby.html) on ReactiveX. public func group<Key>( by selector: @escaping (Item) -> Key ) -> Observable<Observable<Item>> where Key: Hashable { return Observable<Observable<Item>> { t, q, cb in var os: [Key:BehaviorSubject<Item>] = [:] var isCancelled = false self.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: { er in switch er { case let .item(itm): // TODO: Remove cancelled Observables in `os`. let key = selector(itm) if let o = os[key] { o.onNext(itm) } else { guard !isCancelled else { return !os.isEmpty } let o = BehaviorSubject<Item>(initial: itm) os[key] = o q.async { isCancelled = !cb(.item(o.mirror())) } } return true case .complete: if (!isCancelled) { q.async { let _ = cb(.complete) } } for o in os.values { o.onComplete() } case let .error(e): if (!isCancelled) { q.async { let _ = cb(.error(e)) } } for o in os.values { o.onError(e) } } return false }) } } /// Returns an `Observable` that transforms the items emitted by the /// receiver by applying a function to each item. /// /// - seealso: ['Map' operator documentation] /// (http://reactivex.io/documentation/operators/map.html) on ReactiveX. public func map<T>( _ operation: @escaping (Item) -> T ) -> Observable<T> { return Observable<T>() { t, q, cb in self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): return cb(.item(operation(itm))) case .complete: let _ = cb(.complete) case let .error(e): let _ = cb(.error(e)) } return false } } } /// Returns an `Observable` that applies an function to each item /// emitted by the receiver, sequentially, and emit each successive value. /// /// - seealso: ['Scan' operator documentation] /// (http://reactivex.io/documentation/operators/scan.html) on ReactiveX. public func scan( _ operation: @escaping (Item, Item) -> Item ) -> Observable<Item> { return Observable<Item> { t, q, cb in var acc: Item? = nil self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): guard let pv = acc else { acc = itm return cb(er) } acc = operation(pv, itm) return cb(.item(acc!)) default: let _ = cb(er) return false } } } } /// Returns an `Observable` that subdivides items emitted by the /// receiver into `Observable` windows and emits these windows. /// /// The subdivision is determined by a condition function. When the /// function returns `true`, current window completes and a new window /// is created and emitted. /// /// - note: Cancellation of the receiver does not stop the emission of /// emitted `Observable`s. /// /// - note: Observables emitted by the result `Observable` are _hot_ /// even if the receiver is _cold_. See (Observalbe documentation) /// (http://reactivex.io/documentation/observable.html) on ReactiveX. /// /// - seealso: ['Window' operator documentation] /// (http://reactivex.io/documentation/operators/window.html) on ReactiveX. public func window( by cond: @escaping (Item, TimeInterval) -> Bool ) -> Observable<Observable<Item>> { return Observable<Observable<Item>> { t, q, cb in var o: BehaviorSubject<Item>? = nil var isCancelled = false self.subscribe(at: t, on: q, callback: { er in switch er { case let .item(itm): if o == nil || cond(itm, Time.now - t) { o?.onComplete() if (!isCancelled) { o = BehaviorSubject<Item>(initial: itm) isCancelled = !cb(.item(o!.mirror())) return true } else { o = nil return false } } else { o?.onNext(itm) return true } case .complete: o?.onComplete() if (!isCancelled) { let _ = cb(.complete) } case let .error(e): o?.onError(e) if (!isCancelled) { let _ = cb(.error(e)) } } return false }) } } /// A variety of the `Window` operator. This method closes current window /// if its life span exceeds given time interval. /// /// - seealso: ['Window' operator documentation] /// (http://reactivex.io/documentation/operators/window.html) on ReactiveX. /// /// - seealso: `window(by:)` public func windowWith(timer: TimeInterval) -> Observable<Observable<Item>> { var t = TimeInterval.zero return self.window(by: { _, now in guard now - t < timer else { t = now return true } return false }) } /// A variety of the `Window` operator. This method closes current /// window if the nubmer of items it emitted equals to given number. /// /// - seealso: ['Window' operator documentation] /// (http://reactivex.io/documentation/operators/window.html) on ReactiveX. /// /// - seealso: `window(by:)` public func windowWith(count: Int) -> Observable<Observable<Item>> { return self.zipWithIndex().window(by: { z, _ in return count < 1 || z.1 % count == 0 }).map { $0.map { $0.0 } } } /// Returns an `Observable` that transforms each item emitted by the /// receiver to a pair of the item and its index. /// /// - note: The index is 0-based, of course. public func zipWithIndex() -> Observable<(Item, Int)> { return Observable<(Item, Int)> { t, q, cb in var i = -1 return self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): i += 1 return cb(.item((itm, i))) case .complete: let _ = cb(.complete) case let .error(e): let _ = cb(.error(e)) } return false } } } } // MARK: Filtering extension ObservableProtocol { /// Returns an `Observable` that only emit an item from an Observable if a /// particular timespan has passed without it emitting another item. /// /// - seealso: ['Debounce' operator documentation] /// (http://reactivex.io/documentation/operators/debounce.html) on ReactiveX. /// /// - seealso: `throttle()` public func debounce(_ ti: TimeInterval) -> Observable<Item> { return Observable<Item> { t, q, cb in var st = Time.now - ti self.subscribe(at: t, on: q) { er in switch er { case .item(_): let now = Time.now guard now - st > ti else { st = now return true } st = now return cb(er) default: let _ = cb(er) } return false } } } /// Returns an `Observable` that only emits the `i`th item emitted by /// the receiver. /// /// - seealso: ['ElementAt' operator documentation] /// (http://reactivex.io/documentation/operators/elementat.html) on ReactiveX. public func element(at i: Int) -> Observable<Item> { guard i >= 0 else { return Observable<Item>.empty() } return Observable<Item>() { t, q, cb in var j = 0 self.subscribe(at: t, on: q) { er in switch er { case .item(_): guard j >= i else { j += 1 return true } guard j == i else { fatalError("Unreachable.") } let _ = cb(er) && cb(.complete) default: let _ = cb(er) } return false } } } /// Returns an `Observable` that emits only items from the receiver that /// pass a predication test. /// /// - seealso: ['Filter' operator documentation] /// (http://reactivex.io/documentation/operators/filter.html) on ReactiveX. public func filter( _ predication: @escaping (Item) -> Bool ) -> Observable<Item> { return Observable<Item>() { t, q, cb in self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): guard predication(itm) else { return true } return cb(er) default: let _ = cb(er) } return false } } } /// Returns an `Observable` that emits only the first item, or the first /// item that meets a condition, of the receiver. /// /// - seealso: ['First' operator documentation] /// (http://reactivex.io/documentation/operators/first.html) on ReactiveX. public func first( _ cond: @escaping (Item) -> Bool = { _ in true } ) -> Observable<Item> { return Observable<Item>() { t, q, cb in self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): guard cond(itm) else { return true } let _ = cb(er) && cb(.complete) default: let _ = cb(er) } return false } } } /// Returns an `Observable` that only emits the termination notification of /// the receiver. /// /// - seealso: ['IgnoreElements' operator documentation] /// (http://reactivex.io/documentation/operators/ignoreelements.html) on ReactiveX. public func ignore() -> Observable<Item> { return Observable<Item>() { t, q, cb in self.subscribe(at: t, on: q) { er in switch er { case .item(_): return true default: let _ = cb(er) } return false } } } /// Returns an `Observable` that emits only the last item emitted by the /// receiver. /// /// - seealso: ['Last' operator documentation] /// (http://reactivex.io/documentation/operators/last.html) on ReactiveX. public func last() -> Observable<Item> { return Observable<Item>() { t, q, cb in var last: EmittingResult<Item> = .complete self.subscribe(at: t, on: q) { er in switch er { case .item(_): last = er return true case .complete: switch last { case .item(_): let _ = cb(last) && cb(.complete) default: let _ = cb(er) } case .error(_): let _ = cb(er) } return false } } } /// Returns an `Observable` that emits the most recent item emitted by /// receiver at the time the given sampler observable emits an item. /// /// - note: If both `sampler` and the receiver are cold observables, /// the `sampler` starts *after* the receiver starts. There is a latency /// between them. /// /// - note: If the receiver is terminated, normally or by error, the /// result `Observable` does not terminate. /// /// - seealso: ['Sample' operator documentation] /// (http://reactivex.io/documentation/operators/sample.html) on ReactiveX. /// /// - seealso: `sample(interval:)` public func sample<O: ObservableProtocol>(_ sampler: O) -> Observable<Item> { return Observable<Item>() { t, q, cb in var latest: Item? = nil // var cancelled = false self.subscribe(at: t, on: q) { er in guard !cancelled else { return false } switch er { case let .item(itm): latest = itm return true default: return false } } sampler.subscribe(at: t, on: q) { er in assert(!cancelled) switch er { case .item(_): guard let li = latest else { // Sampled but no item. return true } cancelled = !cb(.item(li)) return !cancelled case .complete: let _ = cb(.complete) case let .error(e): let _ = cb(.error(e)) } cancelled = true return false } } } /// Samples the receiver with fixed time intervals. /// /// - seealso: `sample(:)` public func sample(interval ti: TimeInterval) -> Observable<Item> { return self.sample(Observable.interval(ti)) } /// Returns an `Observable` that mirrors the receiver but discards items /// until a specified condition becomes false. /// /// - seealso: ['SkipWhile' operator documentation] /// (http://reactivex.io/documentation/operators/skipwhile.html) on ReactiveX. public func skip(while cond: @escaping (Item) -> Bool) -> Observable<Item> { return Observable<Item> { t, q, cb in var skipping = true self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): if skipping { skipping = cond(itm) } if skipping { return true } return cb(er) default: let _ = cb(er) } return false } } } /// Returns an `Observable` that mirrors the receiver but suppress the /// first `count` items. /// /// - seealso: ['Skip' operator documentation] /// (http://reactivex.io/documentation/operators/skip.html) on ReactiveX. public func skip(_ count: Int) -> Observable<Item> { guard count > 0 else { return self.mirror() } return self.zipWithIndex().skip(while: { return $0.1 < count }).map { $0.0 } } /// Returns an `Observable` that mirrors the receiver but suppress the /// last `n` items. /// /// - seealso: ['Skip' operator documentation] /// (http://reactivex.io/documentation/operators/skip.html) on ReactiveX. public func skip(last n: Int) -> Observable<Item> { guard n > 0 else { return self.mirror() } return Observable<Item> { t, q, cb in var cq = CircularQueue<Item>(capacity: n) self.subscribe(at: t, on: q) { er in switch er { case .item(_): if cq.isFull { let h = cq.head! assert(!h.isTermination) cq.push(item: er) return cb(h) } cq.push(item: er) return true default: let _ = cb(er) } return false } } } /// Returns an `Observable` that mirrors the receiver but discards items /// until a specified observable emits an item or terminates. /// /// - seealso: ['SkipUntil' operator documentation] /// (http://reactivex.io/documentation/operators/skipuntil.html) on ReactiveX. public func skip<O: ObservableProtocol>(until cond: O) -> Observable<Item> { return Observable<Item> { t, q, cb in var stop = false self.subscribe(at: t, on: q, callback: { er in switch er { case .item(_): if stop { return cb(er) } return true default: let _ = cb(er) } return false }) cond.subscribe(at: t, on: emittingQueue, callback: { er in stop = true return false }) } } /// Returns an `Observable` that mirrors items emitted by the receiver /// until given condition becomes false. /// /// - seealso: ['TakeWhile' operator documentation] /// (http://reactivex.io/documentation/operators/takewhile.html) on ReactiveX. public func take(while cond: @escaping (Item) -> Bool) -> Observable<Item> { return Observable<Item>() { t, q, cb in self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): guard cond(itm) else { let _ = cb(.complete) return false } return cb(er) default: let _ = cb(er) return false } } } } /// Returns an `Observable` that emits only the first `count` items /// emitted by the receiver. /// /// - seealso: ['Take' operator documentation] /// (http://reactivex.io/documentation/operators/take.html) on ReactiveX. public func take(_ count: Int) -> Observable<Item> { guard count > 0 else { return Observable<Item>.empty() } return zipWithIndex().take(while: { $0.1 < count }).map { $0.0 } } /// Returns an `Observable` that emits only the final `n` items emitted /// by the receiver. /// /// - seealso: ['TakeLast' operator documentation] /// (http://reactivex.io/documentation/operators/takelast.html) on ReactiveX. public func take(last n: Int) -> Observable<Item> { guard n > 0 else { return self.mirror() } return Observable<Item> { t, q, cb in var cq = CircularQueue<Item>(capacity: n) self.subscribe(at: t, on: q) { er in switch er { case .item(_): cq.push(item: er) return true case .complete: for i in cq.iterator { if !cb(i) { return false } } let _ = cb(.complete) case .error(_): let _ = cb(er) } return false } } } /// Returns an `Observable` that discards any items emitted by the /// receiver after a second observable emits an item or terminates. /// /// - seealso: ['TakeUntil' operator documentation] /// (http://reactivex.io/documentation/operators/takeuntil.html) on ReactiveX. public func take<O: ObservableProtocol>(until cond: O) -> Observable<Item> { return Observable<Item> { t, q, cb in var stop = false cond.subscribe(at: t, on: emittingQueue, callback: { er in stop = true return false }) self.subscribe(at: t, on: q, callback: { er in switch er { case .item(_): if !stop { return cb(er) } let _ = cb(.complete) default: let _ = cb(er) } return false }) } } /// Returns an `Observable` that mirrors the receiver, but for each /// periodic time interval, only emits the first item within it. /// /// - seealso: `debounce()` public func throttle(_ rate: TimeInterval) -> Observable<Item> { guard !rate.isZero else { return self.mirror() } return Observable<Item> { t, q, cb in var i = 0.0 self.subscribe(at: t, on: q) { er in switch er { case .item(_): let span = Time.now - t if span > rate * i { let b = cb(er) if b { i = (span.seconds / rate.seconds).rounded(.down) + 1 } return b } return true default: let _ = cb(er) } return false } } } } extension ObservableProtocol where Item: Equatable { /// Returns an `Observable` that mirrors the emission of the receiver /// but drops items that /// /// - note: This method's behavior is actually `DistinctUntilChange` /// /// - seealso: ['Distinct' operator documentation] /// (http://reactivex.io/documentation/operators/distinct.html) on ReactiveX. /// /// - seealso: `uniq()` public func distinct() -> Observable<Item> { return Observable<Item>() { t, q, cb in var last: Item? = nil self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): guard let pv = last else { last = itm return cb(er) } last = itm return (pv == itm) || cb(er) default: let _ = cb(er) } return false } } } } extension ObservableProtocol where Item: Hashable { /// Returns an `Observable` that mirrors the emission of the receiver /// but suppress all duplicated items. /// /// - note: This method /// /// - seealso: ['Distinct' operator documentation] /// (http://reactivex.io/documentation/operators/distinct.html) on ReactiveX. /// /// - seealso: `distinct()` public func uniq() -> Observable<Item> { return Observable<Item> { t, q, cb in var keys = Set<Int>.init() self.subscribe(at: t, on: q, callback: { er in switch er { case let .item(itm): let key = itm.hashValue guard !keys.contains(key) else { return true } keys.insert(key) return cb(er) default: let _ = cb(er) } return false }) } } } // MARK: Combining extension ObservableProtocol { /// Returns an `Observable` that emits a tuple, which combines the lastest /// items emitted by the receiver and another observable. /// /// - seealso: ['Merge' operator documentation] /// (http://reactivex.io/documentation/operators/merge.html) on ReactiveX. /// /// - seealso: `zip(:)` public func combine<O: ObservableProtocol>( latest that: O ) -> Observable<(Item, O.Item)> { return Observable<(Item, O.Item)> { t, q, cb in var left: Item? = nil var right: O.Item? = nil var count = 2 var isTerminated = false self.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: { er in guard !isTerminated else { return false } switch er { case let .item(itm): left = itm guard let ri = right else { return true } q.async { isTerminated = !cb(.item((itm, ri))) } return true case .complete: count -= 1 if count == 0 { q.async { let _ = cb(.complete) } } case let .error(e): isTerminated = true q.async { let _ = cb(.error(e)) } } return false }) that.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: { er in guard !isTerminated else { return false } switch er { case let .item(itm): right = itm guard let li = left else { return true } q.async { isTerminated = !cb(.item((li, itm))) } return true case .complete: count -= 1 if count == 0 { q.async { let _ = cb(.complete) } } case let .error(e): isTerminated = true q.async { let _ = cb(.error(e)) } } return false }) } } /// Returns an `Observable` that /// /// - note: In other Rx implementations, this method is normally called /// `withLatestFrom`. /// /// - seealso: ['Merge' operator documentation] /// (http://reactivex.io/documentation/operators/merge.html) on ReactiveX. public func zipWith<O: ObservableProtocol>(latest that: O) -> Observable<(Item, O.Item)> { return Observable<(Item, O.Item)> { t, q, cb in var right: O.Item? = nil var isTerminated = false self.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: { er in guard !isTerminated else { return false } switch er { case let .item(itm): guard let ri = right else { return true } q.async { isTerminated = !cb(.item((itm, ri))) } return true case .complete: q.async { let _ = cb(.complete) } case let .error(e): q.async { let _ = cb(.error(e)) } } isTerminated = true return false }) that.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: { er in guard !isTerminated else { return false } switch er { case let .item(itm): right = itm return true case .complete: break case let .error(e): isTerminated = true q.async { let _ = cb(.error(e)) } } return false }) } } /// Returns an `Observable` that combines the emissions of multiple /// observables into one. /// /// - seealso: ['Merge' operator documentation] /// (http://reactivex.io/documentation/operators/merge.html) on ReactiveX. /// /// - seealso: `flatMap(:)`. public static func merge<O: ObservableProtocol>(_ os: O...) -> Observable<Item> where O.Item == Item { return Observable.from(sequence: os).merge() } /// Returns an `Observable` that emits items of given observale before /// mirrors the receiver. /// /// - seealso: ['StartWith' operator documentation] /// (http://reactivex.io/documentation/operators/startwith.html) on ReactiveX. public func start<O: ObservableProtocol>(with that: O) -> Observable<Item> where O.Item == Item { return Observable<Item> { t, q, cb in that.subscribe(at: t, on: q) { er in switch er { case .item(_): return cb(er) case .complete: self.subscribe(at: t, on: q) { er in switch er { case .item(_): return cb(er) default: let _ = cb(er) } return false } case .error(_): let _ = cb(er) } return false } } } /// Returns an `Observable` that combines the emissions of two /// observables into a pair of items. /// /// - note: For simplicity reason, the behavior of this method is not /// same as standard `Zip` operator but it is easily achieved by /// composing operators. /// /// - seealso: ['Zip' operator documentation] /// (http://reactivex.io/documentation/operators/zip.html) on ReactiveX. public func zip<O: ObservableProtocol>(_ that: O) -> Observable<(Item, O.Item)> { return Observable<(Item, O.Item)> { t, q, cb in var left = CircularQueue<Item>(capacity: 4, fixed: false) var right = CircularQueue<O.Item>(capacity: 4, fixed: false) var isTerminated = false self.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue) { er in guard !isTerminated else { return false } switch er { case let .item(itm): let rr = right.pop() guard let r = rr else { left.push(item: er) return true } switch r { case .complete: q.async { let _ = cb(.complete) } isTerminated = true case let .item(ri): q.async { isTerminated = !cb(.item((itm, ri))) } default: fatalError("Unreachable.") } return true case .complete: if left.count == 0 { q.async { let _ = cb(.complete) } isTerminated = true } else { left.push(item: .complete) } case let .error(e): q.async { let _ = cb(.error(e)) } isTerminated = true } return false } that.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue) { er in guard !isTerminated else { return false } switch er { case let .item(itm): guard let l = left.pop() else { right.push(item: er) return true } switch l { case .complete: q.async { let _ = cb(.complete) } isTerminated = true return false case let .item(li): q.async { isTerminated = !cb(.item((li, itm))) } default: fatalError("Unreachable.") } return true case .complete: if right.count == 0 { q.async { let _ = cb(.complete) } isTerminated = true } else { right.push(item: .complete) } case let .error(e): q.async { let _ = cb(.error(e)) } isTerminated = true } return false } } } } extension ObservableProtocol where Item: ObservableProtocol { /// Returns an `Observable` that combines the observables emitted by the /// receiver into one. /// /// - seealso: ['Merge' operator documentation] /// (http://reactivex.io/documentation/operators/merge.html) on ReactiveX. public func merge() -> Observable<Item.Item> { return self.flatMap { $0.mirror() } } /// Returns an `Observable` that mirrors the observable most recently /// emitted by the receiver. /// /// - note: The result `Observable` is terminated when: /// 1. Error occurs in either the latest observable or the receiver, /// 2. Both the latest observable and the receiver complete. /// /// - seealso: ['Switch' operator documentation] /// (http://reactivex.io/documentation/operators/switch.html) on ReactiveX. public func switchLatest() -> Observable<Item.Item> { return Observable<Item.Item> { t, q, cb in var count = 1 var isTerminated = false var current = -1 func subscribe(item: Item, tag: Int) { item.observe(on: emittingQueue) .subscribe(at: Time.now, on: serialQueue, callback: { er in guard !isTerminated else { return false } // NOTE: guard tag == current else { return false } switch er { case .item(_): q.async { isTerminated = !cb(er) } return true case .complete: count -= 1 if count == 0 { q.async { let _ = cb(.complete) } } case .error(_): isTerminated = true q.async { let _ = cb(er) } } return false }) } self.observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: { er in guard !isTerminated else { return false } switch er { case let .item(o): if count == 1 { count = 2 } current += 1 subscribe(item: o, tag: current) return true case .complete: count -= 1 if count == 0 { q.async { let _ = cb(.complete) } } case let .error(e): isTerminated = true q.async { let _ = cb(.error(e)) } } return false }) } } } // MARK: Error Handling extension ObservableProtocol { /// Returns an `Observable` that mirrors the receiver, but when error /// notification is emitted, it tries to recover to an `Observable` derived /// from the error. /// /// - seealso: ['Catch' operator documentation] /// (http://reactivex.io/documentation/operators/catch.html) on ReactiveX. public func `catch`( _ operation: @escaping (Error) -> Observable<Item> ) -> Observable<Item> { return Observable<Item>() { t, q, cb in self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): return cb(.item(itm)) case let .error(e): let o = operation(e) o.subscribe(at: t, on: q, callback: { er in switch er { case .item(_): return cb(er) default: let _ = cb(er) } return false }) case .complete: let _ = cb(.complete) } return false } } } /// Returns an `Observable` that mirrors the receiver, but when error /// notification is emitted, it /// /// - note: To use this operator, the receiver must be ill-behaved. That /// is, it can emit items after emitting error notifications. The only /// way to create such an observable is to use `Observable.init(callback:)`. /// /// - note: To ignore error notification altogether, pass `0` to the /// method. /// /// - seealso: ['Retry' operator documentation] /// (http://reactivex.io/documentation/operators/retry.html) on ReactiveX. /// /// - seealso: `Observable.init(callback:)` public func retry(count: Int) -> Observable<Item> { return Observable<Item>() { t, q, cb in var i = 0 var cancelled = false // NOTE: The receiver IS not well-behaved. Can't use return // value to stop emitting. self.subscribe(at: t, on: q) { er in guard !cancelled else { return false } switch er { case let .item(itm): cancelled = !cb(.item(itm)) return !cancelled case let .error(e): guard count > 0 && i >= count else { if count > 0 { i += 1 } return true } let _ = cb(.error(e)) case .complete: let _ = cb(.complete) } cancelled = true return false } } } } // MARK: Utility extension ObservableProtocol { /// Returns an `Observable` that shifts the emission from an Observable /// forward in time by a particular amount. /// /// - seealso: [`Delay` operator documentation] /// (http://reactivex.io/documentation/operators/delay.html) on ReactiveX. public func delay(_ ti: TimeInterval) -> Observable<Item> { return Observable<Item>() { t, q, cb in emittingQueue.asyncAfter(deadline: DispatchTime.now() + ti.seconds) { self.subscribe(at: Time.now, on: q) { er in return cb(er) } } } } /// Returns an `Observable` that mirrors the receiver and is able to /// execute a registered action if a given condition passes. /// /// - note: The action is executed on the same `DispatchQueue` as /// subscription. /// /// - seealso: [`Do` operator documentation] /// (http://reactivex.io/documentation/operators/do.html) on ReactiveX. public func tap( on cond: @escaping (EmittingResult<Item>) -> Bool, action: @escaping () -> Void ) -> Observable<Item> { return Observable<Item> { t, q, cb in self.subscribe(at: t, on: q, callback: { er in if cond(er) { action() } switch er { case .item(_): return cb(er) default: let _ = cb(er) } return false }) } } /// Returns an `Observable` that emits the time intervals between /// emission of the receiver. /// /// - seealso: [`TimeInterval` operator documentation] /// (http://reactivex.io/documentation/operators/timeinterval.html) on ReactiveX. public func interval() -> Observable<TimeInterval> { return Observable<TimeInterval> { t, q, cb in var it = t self.subscribe(at: t, on: q) { er in let now = Time.now let ti = EmittingResult<TimeInterval>.item(now - it) it = now switch er { case .item(_): return cb(ti) case .complete: let _ = cb(ti) && cb(.complete) case let .error(e): let _ = cb(ti) && cb(.error(e)) } return false } } } /// Returns an `Observable` that mirrors the receiver but it subscribes /// the receiver on a particular `DispatchQueue`. /// /// - note: This is a important method since it's the only way to /// parallel execute chained operators. /// /// - seealso: [`ObserveOn` operator documentation] /// (http://reactivex.io/documentation/operators/observeon.html) on ReactiveX. public func observe(on queue: DispatchQueue) -> Observable<Item> { return Observable<Item> { t, q, cb in var cancelled = false self.subscribe(at: t, on: queue) { er in guard !cancelled else { return false } q.async { cancelled = !cb(er) } return !cancelled } } } /// Returns an `Observable` that mirrors the receiver, but emits an error /// notification if a particular period of time elapses without any emitted /// items. /// /// - seealso: [`Timeout` operator documentation] /// (http://reactivex.io/documentation/operators/timeout.html) on ReactiveX. public func timeout(_ ti: TimeInterval) -> Observable<Item> { return Observable<Item> { t, q, cb in // Last emitting time. var ct = t var isTerminated = false func timer(_ dl: TimeInterval) { serialQueue.asyncAfter(deadline: DispatchTime.now() + dl.seconds, execute: { guard !isTerminated else { return } let dt = Time.now - ct guard dt < ti else { q.async { let _ = cb(.error(RuntimeError.timeout)) } isTerminated = true return } timer(ti - dt) }) } timer(ti) self.observe(on: emittingQueue).subscribe(at: t, on: serialQueue) { er in guard !isTerminated else { return false } switch er { case .item(_): ct = Time.now q.async { isTerminated = !cb(er) } return true default: q.async { let _ = cb(er) } isTerminated = true return false } } } } /// Returns an `Observable` that attaches a timestamp to each item /// emitted by the receiver indicating when it is emitted. /// /// - seealso: [`Timestamp` operator documentation] /// (http://reactivex.io/documentation/operators/timestamp.html) on ReactiveX. public func timestamp() -> Observable<(Item, TimeInterval)> { return Observable<(Item, TimeInterval)> { t, q, cb in self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): return cb(.item((itm, Time.now - t))) case .complete: let _ = cb(.complete) case let .error(e): let _ = cb(.error(e)) } return false } } } } // MARK: Conditional extension ObservableProtocol { /// Returns an `Observable` that determines if all the items emitted /// by the receiver pass a predication test, and then emits the result. /// /// - note: If the receiver is empty or terminated by an error, the /// returned `Observable` emits nothing. /// /// - seealso: ['All' operator documentation] /// (http://reactivex.io/documentation/operators/all.html) on ReactiveX. public func all( _ predication: @escaping (Item) -> Bool ) -> Observable<Bool> { return Observable<Bool> { t, q, cb in var b = false self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): guard !predication(itm) else { b = true return true } let _ = cb(.item(false)) && cb(.complete) case .complete: if !b { // Empty. let _ = cb(.complete) } else { let _ = cb(.item(true)) && cb(.complete) } case let .error(err): let _ = cb(.error(err)) } return false } } } /// Returns an `Observable` that mirrors the emission of the observable /// that first emits. /// /// - seealso: ['Amb' operator documentation] /// (http://reactivex.io/documentation/operators/amb.html) on ReactiveX. public static func amb(_ os: Self...) -> Observable<Item> { return Observable<Item> { t, q, cb in var chosen = -1 for i in 0..<os.count { let o = os[i] o.subscribe(at: t, on: q, callback: { er in if chosen < 0 { chosen = i } if chosen != i { return false } switch er { case .item(_): return cb(er) default: let _ = cb(er) } return false }) } } } /// Returns an `Observable` that emits given default item if the /// receiver emits nothing. /// /// - seealso: ['DefaultIfEmpty' operator documentation] /// (http://reactivex.io/documentation/operators/defaultifempty.html) on ReactiveX. public func defaultItem(_ itm: Item) -> Observable<Item> { return Observable<Item>() { t, q, cb in var isEmpty = true self.subscribe(at: t, on: q) { er in switch er { case .item(_): isEmpty = false return cb(er) case .complete: if isEmpty { let _ = cb(.item(itm)) && cb(.complete) } else { let _ = cb(.complete) } case .error(_): let _ = cb(er) } return false } } } } extension ObservableProtocol where Item: Equatable { /// Returns an `Observable` that determines whether the receiver emits a /// particular item or not, and emits the result. /// /// - seealso: ['Contains' operator documentation] /// (http://reactivex.io/documentation/operators/contains.html) on ReactiveX. public func contains(_ item: Item) -> Observable<Bool> { return Observable<Bool> { t, q, cb in self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): guard itm == item else { return true } if cb(.item(true)) { let _ = cb(.complete) } case let .error(e): let _ = cb(.error(e)) case .complete: if cb(.item(false)) { let _ = cb(.complete) } } return false } } } /// Returns an `Observable` that determines whether the receiver and /// another observable emit the same sequence of items, and then emits the /// result. /// /// - seealso: ['SequenceEqual' operator documentation] /// (http://reactivex.io/documentation/operators/sequenceequal.html) on ReactiveX. public func sequenceEqual<O: ObservableProtocol>(_ that: O) -> Observable<Bool> where O.Item == Item { return Observable<Bool> { t, q, cb in var seq = CircularQueue<Item>(capacity: 16, fixed: false) var hasError = false var top = 0 let lcb = { (er: EmittingResult<(Item, Int)>) -> Bool in guard !hasError else { return false } switch er { case let .item((itm, i)): if i == top { top += 1 seq.push(item: .item(itm)) return true } else { assert(i < top) let h = seq.pop()! switch h { case let .item(hv) where itm == hv: return true default: // Always run user provided callbacks on user // specified queue. q.async { // FIXME: return value of `cb(.item(_))` is ignored. let _ = cb(.item(false)) && cb(.complete) } } } case .complete: guard let last = seq.last, last == EmittingResult<Item>.complete else { top += 1 seq.push(item: .complete) return false } q.async { let _ = cb(.item(seq.count == 1)) && cb(.complete) } case let .error(e): hasError = true q.async { let _ = cb(.error(e)) } } return false } self.zipWithIndex() .observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: lcb) that.zipWithIndex() .observe(on: emittingQueue) .subscribe(at: t, on: serialQueue, callback: lcb) } } } // MARK: Mathematical & Aggregate extension ObservableProtocol { /// Returns an `Observable` that emits items emitted by the receiver, /// and then items emitted by another observable. /// /// - note: This function concat only *2* observables. This is different /// than the standard `Concat` operator. However, you can achieve that /// behavior by calling `concat` as many times as needed. /// /// - note: If the receiver emits an error, the emission of returned /// `Observable` terminates as well. /// /// - seealso: ['Concat' operator documentation] /// (http://reactivex.io/documentation/operators/concat.html) on ReactiveX. /// /// - seealso: `start(with:)` public func concat<O: ObservableProtocol>( _ that: O ) -> Observable<Item> where O.Item == Item { return that.start(with: self) } /// Returns an `Observable` that emits the number of items emitted by /// the receiver. /// /// - note: If the receiver emits only termination notifications, the /// returned `Observable` does not emit `0`, instead it emits the same /// termination notification as the receiver does. /// /// - seealso: ['Count' operator documentation] /// (http://reactivex.io/documentation/operators/count.html) on ReactiveX. public func count() -> Observable<Int> { return self.reduce({ _ in 1 }, { i, _ in i + 1 }) } /// Returns an `Observable` that applies `initial` fucntion to the first /// item emitted by the receiver, and then applies `operation` function /// to all subsequent items, sequentially. It emits only the final value. /// /// - seealso: ['Reduce' operator documentation] /// (http://reactivex.io/documentation/operators/reduce.html) on ReactiveX. public func reduce<T>( _ initial: @escaping (Item) -> T, _ operation: @escaping (T, Item) -> T ) -> Observable<T> { return Observable<T>() { t, q, cb in var acc: T? = nil self.subscribe(at: t, on: q) { er in switch er { case let .item(itm): guard let a = acc else { acc = initial(itm) return true } acc = operation(a, itm) return true case .complete: if let acc = acc { if !cb(.item(acc)) { break } } let _ = cb(.complete) case let .error(e): let _ = cb(.error(e)) } return false } } } /// Reduced verion of `reduce` for the situations where types of `Item` /// of result `Observable` and `Item` of the receiver are same. /// /// - note: The `initial` function just returns the first item intact. public func reduce( _ operation: @escaping (Item, Item) -> Item ) -> Observable<Item> { return self.reduce({ $0 }, operation) } } extension ObservableProtocol where Item: FloatingPoint { /// Returns an `Observable` that calculates the average of numbers /// emitted by the receiver and emits only this average value. /// /// - seealso: ['Average' operator documentation] /// (http://reactivex.io/documentation/operators/average.html) on ReactiveX. public func average() -> Observable<Item> { return self.zipWithIndex().reduce({ a, b in (a.0 + b.0, b.1 + 1) }).map { $0.0 / Item($0.1) } } /// Returns an `Observable` that calculates the sum of numbers /// emitted by the receiver and emits only this sum value. /// /// - seealso: ['Sum' operator documentation] /// (http://reactivex.io/documentation/operators/sum.html) on ReactiveX. public func sum() -> Observable<Item> { return self.reduce(+) } } extension ObservableProtocol where Item: Comparable { /// Returns an `Observable` that determines and emits the maximum-valued /// items emitted by the receiver. /// /// - seealso: ['Max' operator documentation] /// (http://reactivex.io/documentation/operators/max.html) on ReactiveX. public func max() -> Observable<Item> { return self.reduce { $0 > $1 ? $0 : $1 } } /// Returns an `Observable` that determines and emits the minimum-valued /// items emitted by the receiver. /// /// - seealso: ['Min' operator documentation] /// (http://reactivex.io/documentation/operators/min.html) on ReactiveX. public func min() -> Observable<Item> { return self.reduce { $0 < $1 ? $0 : $1 } } }
mit
80accb236b3971e180da73e26cd0563b
32.900218
112
0.471299
4.891571
false
false
false
false
vadymmarkov/Faker
Tests/Fakery/Generators/AddressSpec.swift
3
4446
import Quick import Nimble @testable import Fakery final class AddressSpec: QuickSpec { override func spec() { describe("Address") { var address: Faker.Address! beforeEach { let parser = Parser(locale: "en-TEST") address = Faker.Address(parser: parser) } describe("#city") { it("returns the correct text") { let city = address.city() expect(city).to(equal("North Vadymtown")) } } describe("#streetName") { it("returns the correct text") { let streetName = address.streetName() expect(streetName).to(equal("Vadym Avenue")) } } describe("#secondaryAddress") { it("returns the correct text") { let secondaryAddress = address.secondaryAddress() expect(secondaryAddress).to(match("^Apt. \\d{3}$")) } } describe("#streetAddress") { context("without secondary") { it("returns the correct text") { let streetAddress = address.streetAddress() expect(streetAddress).to(match("^\\d{5} Vadym Avenue$")) } } context("include secondary") { it("returns the correct text") { let streetAddress = address.streetAddress(includeSecondary: true) expect(streetAddress).to(match("^\\d{5} Vadym Avenue Apt. \\d{3}$")) } } } describe("#buildingNumber") { it("returns the correct text") { let buildingNumber = address.buildingNumber() expect(buildingNumber).to(match("^\\d{5}$")) } } describe("#postcode") { context("without the state abbreviation") { it("returns the correct text") { let postcode = address.postcode() expect(postcode).to(match("^\\d{5}-\\d{4}$")) } } context("with the state abbreviation") { it("returns the correct text") { let postcode = address.postcode(stateAbbreviation: "CA") expect(postcode).to(match("^900\\d{2}$")) } } context("with the wrong state abbreviation") { it("returns the correct text") { let postcode = address.postcode(stateAbbreviation: "TE") expect(postcode).to(beEmpty()) } } } describe("#timeZone") { it("returns the correct text") { let timeZone = address.timeZone() expect(timeZone).to(equal("America/Los_Angeles")) } } describe("#streetSuffix") { it("returns the correct text") { let streetSuffix = address.streetSuffix() expect(streetSuffix).to(equal("Avenue")) } } describe("#citySuffix") { it("returns the correct text") { let citySuffix = address.citySuffix() expect(citySuffix).to(equal("town")) } } describe("#cityPrefix") { it("returns the correct text") { let cityPrefix = address.cityPrefix() expect(cityPrefix).to(equal("North")) } } describe("#stateAbbreviation") { it("returns the correct text") { let stateAbbreviation = address.stateAbbreviation() expect(stateAbbreviation).to(equal("CA")) } } describe("#state") { it("returns the correct text") { let state = address.state() expect(state).to(equal("California")) } } describe("#county") { it("returns the correct text") { let country = address.county() expect(country).to(equal("Autauga County")) } } describe("#country") { it("returns the correct text") { let country = address.country() expect(country).to(equal("United States of America")) } } describe("#countryCode") { it("returns the correct text") { let countryCode = address.countryCode() expect(countryCode).to(equal("US")) } } describe("#latitude") { it("returns non-zero value") { let latitude = address.latitude() expect(latitude).notTo(equal(0)) } } describe("#longitude") { it("returns non-zero value") { let longitude = address.longitude() expect(longitude).notTo(equal(0)) } } } } }
mit
7d318b764983c9a0d65e2ea54ed6638d
26.7875
80
0.533963
4.636079
false
false
false
false
entaq/Cliq
Cliq/Cliq/CliqListPhotosViewController.swift
1
3319
import UIKit class CliqListPhotosViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { var cliqId = "" var photos = [PFObject]() @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.loadPhotos() } func loadPhotos() { collectionView.registerNib(UINib(nibName: "CliqCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "photoCell") // trying to load all the photos that belong to cliqAlbum // id of the cliq album would come in handy for a query of those photos //query all the user photos that belong to the cliqAlbum which the user originally selected from the home controller let query = PFQuery(className: "UserPhoto") query.whereKey("cliqGroup", equalTo: PFObject(outDataWithClassName: "CliqAlbum", objectId: cliqId)) query.orderByDescending("createdAt") query.includeKey("creator") query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in if error == nil { if let objects = objects as [PFObject]! { self.photos = objects print(self.photos.count) self.collectionView.reloadData() } } else { print(error?.description) } } } // MARK: Collection view data source methods func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("photoCell", forIndexPath: indexPath) as! CliqCollectionViewCell let userPhoto = photos[indexPath.row] as PFObject if let userPhotoFile = userPhoto["imageFile"] as? PFFile { cell.cliqImage.file = userPhotoFile cell.cliqImage.loadInBackground({ (image: UIImage?, error: NSError?) -> Void in cell.setNeedsLayout() }) if let creator = userPhoto["creator"] as? PFObject { if let facebookId = creator["facebookId"] as? String { cell.setCliqCreator(facebookId) } } } return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
976a4a7771d7b48987c081e9e192e4a1
32.525253
137
0.591745
5.990975
false
false
false
false
stephentyrone/swift
test/IRGen/autolink-runtime-compatibility.swift
3
3272
// REQUIRES: OS=macosx // Doesn't autolink compatibility library because autolinking is disabled // RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -target x86_64-apple-macosx10.9 -disable-autolinking-runtime-compatibility -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // RUN: %target-swift-frontend -disable-autolinking-runtime-compatibility-dynamic-replacements -runtime-compatibility-version 5.0 -disable-autolinking-runtime-compatibility -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Doesn't autolink compatibility library because runtime compatibility library is disabled // RUN: %target-swift-frontend -runtime-compatibility-version none -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Doesn't autolink compatibility library because target OS doesn't need it // RUN: %target-swift-frontend -target x86_64-apple-macosx10.24 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=NO-FORCE-LOAD %s // Only autolinks 5.1 compatibility library because target OS has 5.1 // RUN: %target-swift-frontend -target x86_64-apple-macosx10.15 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s // Autolinks because compatibility library was explicitly asked for // RUN: %target-swift-frontend -runtime-compatibility-version 5.0 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD %s // RUN: %target-swift-frontend -runtime-compatibility-version 5.1 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s // RUN: %target-swift-frontend -target x86_64-apple-macosx10.24 -runtime-compatibility-version 5.0 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD %s // RUN: %target-swift-frontend -target x86_64-apple-macosx10.24 -runtime-compatibility-version 5.1 -emit-ir -parse-stdlib %s | %FileCheck -check-prefix=FORCE-LOAD-51 %s public func foo() {} // NO-FORCE-LOAD-NOT: FORCE_LOAD // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibility50"} // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibility51"} // NO-FORCE-LOAD-NOT: !{!"-lswiftCompatibilityDynamicReplacements"} // FORCE-LOAD: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-DAG: [[AUTOLINK_SWIFT_COMPAT:![0-9]+]] = !{!"-lswiftCompatibility50"} // FORCE-LOAD-DAG: !{!"-lswiftCompatibility51"} // FORCE-LOAD-DAG: !{!"-lswiftCompatibilityDynamicReplacements"} // FORCE-LOAD-DAG: !llvm.linker.options = !{{{.*}}[[AUTOLINK_SWIFT_COMPAT]]{{[,}]}} // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-51: declare {{.*}} @"_swift_FORCE_LOAD_$_swiftCompatibility51" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements" // FORCE-LOAD-51-DAG: [[AUTOLINK_SWIFT_COMPAT:![0-9]+]] = !{!"-lswiftCompatibility51"} // FORCE-LOAD-51-DAG: !llvm.linker.options = !{{{.*}}[[AUTOLINK_SWIFT_COMPAT]]{{[,}]}} // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibility50" // FORCE-LOAD-51-NOT: @"_swift_FORCE_LOAD_$_swiftCompatibilityDynamicReplacements"
apache-2.0
c1092e6e36f51cba268bd4b2ac2f186f
73.363636
242
0.741137
3.579869
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Part 4 - Alien Adventure 2/Enums/Enums.playground/Pages/Raw values.xcplaygroundpage/Contents.swift
1
797
//: [Previous](@previous) //: ## Raw values // The enum, MazeDirection, is assigned rawValues that are Ints. enum MazeDirection: Int { case up = 0, right, down, left } // In Swift, raw values can be of type String or any of the numeric types. enum AmericanLeagueWest: String { case athletics = "Oakland" case astros = "Houston" case angels = "Los Angeles" case mariners = "Seattle" case rangers = "Arlington" } // Here, DrinkSize is assigned Int rawValues representing volume. enum DrinkSize: Int { case small = 12 case medium = 16 case large = 20 } // Here's how rawValues are accessed: var message = "I hope the A's stay in \(AmericanLeagueWest.athletics.rawValue)" var sugar = "A \(DrinkSize.small.rawValue) oz Coke has 33 g of sugar." //: [Next](@next)
mit
0e27c4115aed746ea30d234743c3a9c3
27.464286
79
0.68256
3.542222
false
false
false
false
andersio/MantleData
MantleData/Editor.swift
1
7058
// // Editor.swift // MantleData // // Created by Anders on 1/5/2016. // Copyright © 2016 Anders. All rights reserved. // import ReactiveSwift import enum Result.NoError /// `Editor` takes any `MutablePropertyProtocol` conforming types as its source, and /// exposes a two-way binding interface for UIControl. /// /// `Editor` would maintain a cached copy of the value. shall any conflict or /// modification has been occured, this cached copy would be the latest version. /// Therefore, you must explicitly commit the `Editor` at the time you need the /// latest value. /// /// - Warning: Since the `UIControl` subclasses are not thread-safe, this class /// inherits the caveat. public class Editor<SourceValue: Equatable, TargetValue: Equatable> { private let resetSignal: Signal<(), NoError> private let resetObserver: Signal<(), NoError>.Observer private let transform: EditorTransform<SourceValue, TargetValue> private let source: AnyMutableProperty<SourceValue> private weak var target: _Editable! private var targetGetter: (() -> TargetValue)! private var targetSetter: ((TargetValue) -> Void)! private let _cache: MutableProperty<SourceValue> public var cache: Property<SourceValue> { return Property(_cache) } private let mergePolicy: EditorMergePolicy<SourceValue, TargetValue> private var hasUserInitiatedChanges = false private var observerDisposable: CompositeDisposable public required init<Property: MutablePropertyProtocol>(source property: Property, mergePolicy: EditorMergePolicy<SourceValue, TargetValue>, transform: EditorTransform<SourceValue, TargetValue>) where Property.Value == SourceValue { self.source = AnyMutableProperty(property) self.mergePolicy = mergePolicy self.transform = transform observerDisposable = CompositeDisposable() (resetSignal, resetObserver) = Signal<(), NoError>.pipe() /// Thread safety is not a concern. _cache = MutableProperty(property.value) observerDisposable += property.signal.observeValues { value in self._cache.value = value } } public func bindTo<E: Editable>(_ control: E, until: SignalProducer<(), NoError>) where E.Value == TargetValue { assert(target == nil) until.startWithCompleted { [weak self] in self?.cleanUp() } target = control target.subscribeToChanges(with: self) targetGetter = { [unowned control] in control.value } targetSetter = { [unowned control] in control.value = $0 } observerDisposable += source.producer .startWithValues { [unowned self] value in self.targetSetter(self.transform.sourceToTarget(value)) } } public func bindTo<E: Editable>(_ target: E, until: Signal<(), NoError>) where E.Value == TargetValue { bindTo(target, until: SignalProducer(signal: until)) } public func reset() { hasUserInitiatedChanges = false observerDisposable.dispose() observerDisposable = CompositeDisposable() resetObserver.send(value: ()) _cache.value = source.value observerDisposable += source.producer .startWithValues { [unowned self] value in self.targetSetter(self.transform.sourceToTarget(value)) } } public func commit() { if source.value != _cache.value { source.value = _cache.value } } @objc public func receive() { let targetValue = transform.targetToSource(targetGetter()) if _cache.value == targetValue { return } if !hasUserInitiatedChanges { hasUserInitiatedChanges = true observerDisposable.dispose() _cache.value = targetValue source.signal .take(until: resetSignal) .observeValues { [unowned self] newSourceValue in /// conflict let currenttargetValue = self.transform.targetToSource(self.targetGetter()) if newSourceValue != currenttargetValue { switch self.mergePolicy { case .overwrite: self._cache.value = currenttargetValue case let .notify(handler): let newValue = handler(newSourceValue, currenttargetValue) self.targetSetter(self.transform.sourceToTarget(newValue)) self._cache.value = newValue } } } } else { _cache.value = targetValue } } private func cleanUp() { observerDisposable.dispose() target?.unsubscribeToChanges(with: self) resetObserver.sendCompleted() } deinit { cleanUp() } } public protocol EditorProtocol { associatedtype _SourceValue: Equatable associatedtype _TargetValue: Equatable init<Property: MutablePropertyProtocol>(source property: Property, mergePolicy: EditorMergePolicy<_SourceValue, _TargetValue>, transform: EditorTransform<_SourceValue, _TargetValue>) where Property.Value == _SourceValue } extension EditorProtocol where _SourceValue == _TargetValue { public init<Property: MutablePropertyProtocol>(source property: Property, mergePolicy: EditorMergePolicy<_SourceValue, _TargetValue>) where Property.Value == _SourceValue { self.init(source: property, mergePolicy: mergePolicy, transform: EditorTransform()) } } extension Editor: EditorProtocol, _EditorProtocol { public typealias _SourceValue = SourceValue public typealias _TargetValue = TargetValue } public struct EditorTransform<SourceValue: Equatable, TargetValue: Equatable> { public let sourceToTarget: (SourceValue) -> TargetValue public let targetToSource: (TargetValue) -> SourceValue public init(sourceToTarget forwardAction: @escaping (SourceValue) -> TargetValue, targetToSource backwardAction: @escaping (TargetValue) -> SourceValue) { sourceToTarget = forwardAction targetToSource = backwardAction } } public protocol EditorTransformProtocol { associatedtype _SourceValue: Equatable associatedtype _TargetValue: Equatable init(sourceToTarget forwardAction: @escaping (_SourceValue) -> _TargetValue, targetToSource backwardAction: @escaping (_TargetValue) -> _SourceValue) } extension EditorTransform: EditorTransformProtocol { public typealias _SourceValue = SourceValue public typealias _TargetValue = TargetValue } extension EditorTransformProtocol where _SourceValue == _TargetValue { public init() { self.init(sourceToTarget: { $0 }, targetToSource: { $0 }) } } /// `EditorMergePolicy` specifies how an `Editor` should handle a conflict between /// the source property and the target UI control. public enum EditorMergePolicy<SourceValue: Equatable, TargetValue: Equatable> { /// Overwrite the source. case overwrite /// Overwrite both the source and target with the returned value of /// the custom handler. case notify(handler: (_ sourceVersion: SourceValue, _ targetVersion: SourceValue) -> SourceValue) } /// Internal protocol for EditorPool. internal protocol _EditorProtocol: class { func reset() func commit() } /// `Editable` describes the requirement of an `Editor` bindable control. public protocol Editable: _Editable { associatedtype Value: Equatable var value: Value { get set } } public protocol _Editable: class { func subscribeToChanges<SourceValue, TargetValue>(with editor: Editor<SourceValue, TargetValue>) func unsubscribeToChanges<SourceValue, TargetValue>(with editor: Editor<SourceValue, TargetValue>) }
mit
3d2e9f6bfb92e2f401e0f002b0bd1bcb
31.520737
233
0.750319
4.326793
false
false
false
false
skedgo/tripkit-ios
Tests/TripKitUITests/vendor/RxTest/Event+Equatable.swift
3
3693
// // Event+Equatable.swift // RxTest // // Created by Krunoslav Zaher on 12/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import Foundation internal func equals<Element: Equatable>(lhs: Event<Element>, rhs: Event<Element>) -> Bool { switch (lhs, rhs) { case (.completed, .completed): return true case let (.error(e1), .error(e2)): #if os(Linux) return "\(e1)" == "\(e2)" #else let error1 = e1 as NSError let error2 = e2 as NSError return error1.domain == error2.domain && error1.code == error2.code && "\(e1)" == "\(e2)" #endif case let (.next(v1), .next(v2)): return v1 == v2 default: return false } } internal func equals<Element: Equatable>(lhs: Event<Element?>, rhs: Event<Element?>) -> Bool { switch (lhs, rhs) { case (.completed, .completed): return true case let (.error(e1), .error(e2)): #if os(Linux) return "\(e1)" == "\(e2)" #else let error1 = e1 as NSError let error2 = e2 as NSError return error1.domain == error2.domain && error1.code == error2.code && "\(e1)" == "\(e2)" #endif case let (.next(v1), .next(v2)): return v1 == v2 default: return false } } internal func equals<Element: Equatable>(lhs: SingleEvent<Element>, rhs: SingleEvent<Element>) -> Bool { switch (lhs, rhs) { case let (.failure(e1), .failure(e2)): #if os(Linux) return "\(e1)" == "\(e2)" #else let error1 = e1 as NSError let error2 = e2 as NSError return error1.domain == error2.domain && error1.code == error2.code && "\(e1)" == "\(e2)" #endif case let (.success(v1), .success(v2)): return v1 == v2 default: return false } } internal func equals<Element: Equatable>(lhs: MaybeEvent<Element>, rhs: MaybeEvent<Element>) -> Bool { switch (lhs, rhs) { case (.completed, .completed): return true case let (.error(e1), .error(e2)): #if os(Linux) return "\(e1)" == "\(e2)" #else let error1 = e1 as NSError let error2 = e2 as NSError return error1.domain == error2.domain && error1.code == error2.code && "\(e1)" == "\(e2)" #endif case let (.success(v1), .success(v2)): return v1 == v2 default: return false } } /// Compares two `CompletableEvent` events. /// /// In case `Error` events are being compared, they are equal in case their `NSError` representations are equal (domain and code) /// and their string representations are equal. extension CompletableEvent: Equatable { public static func == (lhs: CompletableEvent, rhs: CompletableEvent) -> Bool { switch (lhs, rhs) { case (.completed, .completed): return true case let (.error(e1), .error(e2)): #if os(Linux) return "\(e1)" == "\(e2)" #else let error1 = e1 as NSError let error2 = e2 as NSError return error1.domain == error2.domain && error1.code == error2.code && "\(e1)" == "\(e2)" #endif default: return false } } } extension Event: Equatable where Element: Equatable { public static func == (lhs: Event<Element>, rhs: Event<Element>) -> Bool { equals(lhs: lhs, rhs: rhs) } } extension MaybeEvent: Equatable where Element: Equatable { public static func == (lhs: MaybeEvent<Element>, rhs: MaybeEvent<Element>) -> Bool { equals(lhs: lhs, rhs: rhs) } }
apache-2.0
8be22edccd6aa0013f97ad6c696845f8
29.512397
129
0.554713
3.706827
false
false
false
false
superk589/DereGuide
DereGuide/Unit/Simulation/View/UnitSimulationModeSelectionCell.swift
2
1376
// // UnitSimulationModeSelectionCell.swift // DereGuide // // Created by zzk on 2017/5/16. // Copyright © 2017 zzk. All rights reserved. // import UIKit import SnapKit class UnitSimulationModeSelectionCell: UITableViewCell { let leftLabel = UILabel() var rightLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) leftLabel.font = .systemFont(ofSize: 16) contentView.addSubview(leftLabel) leftLabel.snp.makeConstraints { (make) in make.left.equalTo(10) make.top.equalTo(10) make.bottom.equalTo(-10) } rightLabel.font = .systemFont(ofSize: 16) rightLabel.textColor = .darkGray contentView.addSubview(rightLabel) rightLabel.snp.makeConstraints { (make) in make.right.equalTo(-10) make.centerY.equalTo(leftLabel) } selectionStyle = .none } func setup(with title: String, rightDetail: String, rightColor: UIColor) { leftLabel.text = title rightLabel.text = rightDetail rightLabel.textColor = rightColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
dc35c5365e69c86a321a31a9a788f741
25.960784
79
0.624727
4.757785
false
false
false
false
littleHH/WarePush
WarePush/Charts-master/ChartsDemo-OSX/ChartsDemo-OSX/Demos/RadarDemoViewController.swift
24
1461
// // RadarDemoViewController.swift // ChartsDemo-OSX // // 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 Cocoa import Charts open class RadarDemoViewController: NSViewController { @IBOutlet var radarChartView: RadarChartView! override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let ys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) } let ys2 = Array(1..<10).map { x in return cos(Double(x) / 2.0 / 3.141) } let yse1 = ys1.enumerated().map { x, y in return RadarChartDataEntry(value: y) } let yse2 = ys2.enumerated().map { x, y in return RadarChartDataEntry(value: y) } let data = RadarChartData() let ds1 = RadarChartDataSet(values: yse1, label: "Hello") ds1.colors = [NSUIColor.red] data.addDataSet(ds1) let ds2 = RadarChartDataSet(values: yse2, label: "World") ds2.colors = [NSUIColor.blue] data.addDataSet(ds2) self.radarChartView.data = data self.radarChartView.chartDescription?.text = "Radarchart Demo" } override open func viewWillAppear() { self.radarChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0) } }
apache-2.0
edaedf7c9b7f94869abbad934b57a061
30.085106
88
0.635866
3.927419
false
false
false
false
andyyhope/Elbbbird
Elbbbird/Protocol/Extension/UITableView+ReusableView.swift
1
2147
// // UITableView+Cell.swift // SegueHandlerProtocolTest // // Created by Andyy Hope on 4/01/2016. // Copyright © 2016 Punters. All rights reserved. // import UIKit public extension UITableView { // MARK: - Register Cell Class public func register<T: UITableViewCell where T: ReusableView>(_: T.Type) { registerClass(T.self, forCellReuseIdentifier: T.reuseIdentifier) } // MARK: - Register Cell Class with Nib public func register<T: UITableViewCell where T: ReusableView, T: NibLoadableView>(_: T.Type) { let bundle = NSBundle(forClass: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) registerNib(nib, forCellReuseIdentifier: T.reuseIdentifier) } // MARK: - Register Header Footer Class public func register<T: UITableViewHeaderFooterView where T: ReusableView>(_: T.Type) { registerClass(T.self, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier) } // MARK: - Register Header Footer Class with Nib public func register<T: UITableViewHeaderFooterView where T: ReusableView, T: NibLoadableView>(_: T.Type) { let bundle = NSBundle(forClass: T.self) let nib = UINib(nibName: T.nibName, bundle: bundle) registerNib(nib, forHeaderFooterViewReuseIdentifier: T.reuseIdentifier) } // MARK: - Deqeueing Cell public func dequeueReusableCell<T: UITableViewCell where T: ReusableView>(forIndexPath indexPath: NSIndexPath) -> T { guard let cell = dequeueReusableCellWithIdentifier(T.reuseIdentifier, forIndexPath: indexPath) as? T else { fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)") } return cell } public func dequeueReusableHeaderFooter<T: UITableViewHeaderFooterView where T: ReusableView>() -> T { guard let headerFooter = dequeueReusableHeaderFooterViewWithIdentifier(T.reuseIdentifier) as? T else { fatalError("Could not dequeue cell with identifier: \(T.reuseIdentifier)") } return headerFooter } }
gpl-3.0
192fc8514b7b692ce753ff069e2f6e94
34.180328
121
0.67055
5.121718
false
false
false
false
frtlupsvn/Vietnam-To-Go
Pods/Former/Former/RowFormers/SelectorDatePickerRowFormer.swift
1
4572
// // SelectorDatePickerRowFormer.swift // Former-Demo // // Created by Ryo Aoyama on 8/24/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public protocol SelectorDatePickerFormableRow: FormableRow { var selectorDatePicker: UIDatePicker? { get set } // Needs NOT to set instance. var selectorAccessoryView: UIView? { get set } // Needs NOT to set instance. func formTitleLabel() -> UILabel? func formDisplayLabel() -> UILabel? } public final class SelectorDatePickerRowFormer<T: UITableViewCell where T: SelectorDatePickerFormableRow> : BaseRowFormer<T>, Formable, UpdatableSelectorForm { // MARK: Public override public var canBecomeEditing: Bool { return enabled } public var date: NSDate = NSDate() public var inputAccessoryView: UIView? public var titleDisabledColor: UIColor? = .lightGrayColor() public var displayDisabledColor: UIColor? = .lightGrayColor() public var titleEditingColor: UIColor? public var displayEditingColor: UIColor? public private(set) final lazy var selectorView: UIDatePicker = { [unowned self] in let datePicker = UIDatePicker() datePicker.addTarget(self, action: "dateChanged:", forControlEvents: .ValueChanged) return datePicker }() public required init(instantiateType: Former.InstantiateType = .Class, cellSetup: (T -> Void)? = nil) { super.init(instantiateType: instantiateType, cellSetup: cellSetup) } public final func onDateChanged(handler: (NSDate -> Void)) -> Self { onDateChanged = handler return self } public final func displayTextFromDate(handler: (NSDate -> String)) -> Self { displayTextFromDate = handler return self } public override func update() { super.update() cell.selectorDatePicker = selectorView cell.selectorAccessoryView = inputAccessoryView let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() displayLabel?.text = displayTextFromDate?(date) ?? "\(date)" if self.enabled { _ = titleColor.map { titleLabel?.textColor = $0 } _ = displayTextColor.map { displayLabel?.textColor = $0 } titleColor = nil displayTextColor = nil } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .blackColor() } titleLabel?.textColor = titleDisabledColor displayLabel?.textColor = displayDisabledColor } } public override func cellSelected(indexPath: NSIndexPath) { former?.deselect(true) } public func editingDidBegin() { if enabled { let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .blackColor() } _ = titleEditingColor.map { titleLabel?.textColor = $0 } _ = displayEditingColor.map { displayEditingColor = $0 } isEditing = true } } public func editingDidEnd() { isEditing = false let titleLabel = cell.formTitleLabel() let displayLabel = cell.formDisplayLabel() if enabled { _ = titleColor.map { titleLabel?.textColor = $0 } _ = displayTextColor.map { displayLabel?.textColor = $0 } titleColor = nil displayTextColor = nil } else { if titleColor == nil { titleColor = titleLabel?.textColor ?? .blackColor() } if displayTextColor == nil { displayTextColor = displayLabel?.textColor ?? .blackColor() } titleLabel?.textColor = titleDisabledColor displayLabel?.textColor = displayDisabledColor } } // MARK: Private private final var onDateChanged: (NSDate -> Void)? private final var displayTextFromDate: (NSDate -> String)? private final var titleColor: UIColor? private final var displayTextColor: UIColor? private dynamic func dateChanged(datePicker: UIDatePicker) { let date = datePicker.date self.date = date cell.formDisplayLabel()?.text = displayTextFromDate?(date) ?? "\(date)" onDateChanged?(date) } }
mit
8c9ea8c0e783e471211e20a13454aef2
35.870968
107
0.636185
5.409467
false
false
false
false
yangyouyong0/SwiftLearnLog
Photomania_Starter/Photomania/Five100px.swift
1
10160
// // Five100px.swift // Photomania // // Created by Essan Parto on 2014-09-25. // Copyright (c) 2014 Essan Parto. All rights reserved. // import UIKit @objc public protocol ResponseCollectionSerializable { static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self] } extension Request { public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) ->Void)-> Self { let serializer:Serializer = {(request, response, data)in let JSONSerializer = Request.JSONResponseSerializer(options: NSJSONReadingOptions.AllowFragments) let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data) if response != nil && JSON != nil { return (T.collection(response: response!, representation:JSON!),nil) } else { return (nil, serializationError) } } return response(serializer:serializer,completionHandler:{ (request, response, object, error) in completionHandler(request, response, object as? [T],error) }) } } @objc public protocol ResponseObjectSerializable{ init(response:NSHTTPURLResponse, representation: AnyObject) } extension Request { public func responseObject<T:ResponseObjectSerializable>(completionHandler:(NSURLRequest,NSHTTPURLResponse?,T?,NSError?)->Void)->Self { let serializer:Serializer = {(request,response,data)in let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let (JSON:AnyObject?, serializationError) = JSONSerializer(request,response,data) if response != nil && JSON != nil { return (T(response: response!, representation: JSON!),nil) } else { return (nil, serializationError) } } return response(serializer:serializer, completionHandler:{ (request,response,object,error)in completionHandler(request,response,object as? T, error) }) } } extension Request { class func imageResponseSerializer() -> Serializer { return { request, response, data in if data == nil { return (nil,nil) } let image = UIImage(data: data!, scale: UIScreen.mainScreen().scale) return (image, nil) } } func responseImage(completionHandler:(NSURLRequest,NSHTTPURLResponse?,UIImage?,NSError?)->Void)-> Self { return response(serializer:Request.imageResponseSerializer(),completionHandler:{ (request,response,image,error) in completionHandler(request,response,image as? UIImage,error) }) } } struct Five100px { enum Router: URLRequestConvertible { static let baseURLString = "https://api.500px.com/v1" static let consumerKey = "V9X5a6IBNPELMd6Af5aWTVodK2itnz1ljbf5sPnH" case PopularPhotos(Int) case PhotoInfo(Int, ImageSize) case Comments(Int, Int) var URLRequest: NSURLRequest { let (path: String , parameters: [String: AnyObject]) = { switch self { case .PopularPhotos (let page): let params = ["consumer_key": Router.consumerKey, "page": "\(page)", "feature": "popular", "rpp": "50", "include_store": "store_download", "include_states":"votes"] return ("/photos",params) case .PhotoInfo(let photoID, let imageSize): var params = ["consumer_key":Router.consumerKey, "image_size":"\(imageSize.rawValue)"] return ("/photos/\(photoID)",params) case .Comments(let photoID, let commetsPage): var params = ["consumer_key":Router.consumerKey, "comments":"1", "comments_page":"\(commetsPage)"] return ("/photos/\(photoID)/comments",params) } }() let URL = NSURL(string: Router.baseURLString) let URLRequest = NSURLRequest(URL: URL!.URLByAppendingPathComponent(path)) let encoding = ParameterEncoding.URL return encoding.encode(URLRequest, parameters: parameters).0 } } enum ImageSize: Int { case Tiny = 1 case Small = 2 case Medium = 3 case Large = 4 case XLarge = 5 } enum Category: Int, Printable { case Uncategorized = 0, Celebrities, Film, Journalism, Nude, BlackAndWhite, StillLife, People, Landscapes, CityAndArchitecture, Abstract, Animals, Macro, Travel, Fashion, Commercial, Concert, Sport, Nature, PerformingArts, Family, Street, Underwater, Food, FineArt, Wedding, Transportation, UrbanExploration var description: String { get { switch self { case .Uncategorized: return "Uncategorized" case .Celebrities: return "Celebrities" case .Film: return "Film" case .Journalism: return "Journalism" case .Nude: return "Nude" case .BlackAndWhite: return "Black And White" case .StillLife: return "Still Life" case .People: return "People" case .Landscapes: return "Landscapes" case .CityAndArchitecture: return "City And Architecture" case .Abstract: return "Abstract" case .Animals: return "Animals" case .Macro: return "Macro" case .Travel: return "Travel" case .Fashion: return "Fashion" case .Commercial: return "Commercial" case .Concert: return "Concert" case .Sport: return "Sport" case .Nature: return "Nature" case .PerformingArts: return "Performing Arts" case .Family: return "Family" case .Street: return "Street" case .Underwater: return "Underwater" case .Food: return "Food" case .FineArt: return "Fine Art" case .Wedding: return "Wedding" case .Transportation: return "Transportation" case .UrbanExploration: return "Urban Exploration" } } } } } class PhotoInfo: NSObject, ResponseObjectSerializable { let id: Int let url: String var name: String? var favoritesCount: Int? var votesCount: Int? var commentsCount: Int? var highest: Float? var pulse: Float? var views: Int? var camera: String? var focalLength: String? var shutterSpeed: String? var aperture: String? var iso: String? var category: Five100px.Category? var taken: String? var uploaded: String? var desc: String? var username: String? var fullname: String? var userPictureURL: String? init(id: Int, url: String) { self.id = id self.url = url } required init(response: NSHTTPURLResponse, representation: AnyObject) { self.id = representation.valueForKeyPath("photo.id") as! Int self.url = representation.valueForKeyPath("photo.image_url") as! String self.favoritesCount = representation.valueForKeyPath("photo.favorites_count") as? Int self.votesCount = representation.valueForKeyPath("photo.votes_count") as? Int self.commentsCount = representation.valueForKeyPath("photo.comments_count") as? Int self.highest = representation.valueForKeyPath("photo.highest_rating") as? Float self.pulse = representation.valueForKeyPath("photo.rating") as? Float self.views = representation.valueForKeyPath("photo.times_viewed") as? Int self.camera = representation.valueForKeyPath("photo.camera") as? String self.focalLength = representation.valueForKeyPath("photo.focal_length") as? String self.shutterSpeed = representation.valueForKeyPath("photo.shutter_speed") as? String self.aperture = representation.valueForKeyPath("photo.aperture") as? String self.iso = representation.valueForKeyPath("photo.iso") as? String self.taken = representation.valueForKeyPath("photo.taken_at") as? String self.uploaded = representation.valueForKeyPath("photo.created_at") as? String self.desc = representation.valueForKeyPath("photo.description") as? String self.name = representation.valueForKeyPath("photo.name") as? String self.username = representation.valueForKeyPath("photo.user.username") as? String self.fullname = representation.valueForKeyPath("photo.user.fullname") as? String self.userPictureURL = representation.valueForKeyPath("photo.user.userpic_url") as? String } override func isEqual(object: AnyObject!) -> Bool { return (object as! PhotoInfo).id == self.id } override var hash: Int { return (self as PhotoInfo).id } } //class Comment { // let userFullname: String // let userPictureURL: String // let commentBody: String // // init(JSON: AnyObject) { // userFullname = JSON.valueForKeyPath("user.fullname") as! String // userPictureURL = JSON.valueForKeyPath("user.userpic_url") as! String // commentBody = JSON.valueForKeyPath("body") as! String // } //} final class Comment:ResponseCollectionSerializable { @objc static func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Comment] { var comments = [Comment]() for comment in representation.valueForKeyPath("comments") as! [NSDictionary] { comments.append(Comment(JSON: comment)) } return comments } let userFullname: String let userPictureURL: String let commentBody: String init(JSON:AnyObject){ userFullname = JSON.valueForKeyPath("user.fullname") as! String userPictureURL = JSON.valueForKeyPath("user.userpic_url") as! String commentBody = JSON.valueForKeyPath("body") as! String } }
apache-2.0
d03b334b00bfa6965fe1db9daaab950f
35.6787
311
0.62874
4.71243
false
false
false
false
Sherlouk/IGListKit
Examples/Examples-tvOS/IGListKitExamples/ViewControllers/NestedAdapterViewController.swift
4
2106
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import IGListKit final class NestedAdapterViewController: UIViewController, IGListAdapterDataSource { lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0) }() let collectionView = IGListCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) let data = [ "Most Recent", 10, "Recently Watched", 16, "New Arrivals", 20 ] as [Any] override func viewDidLoad() { super.viewDidLoad() collectionView.backgroundColor = .clear view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } // MARK: IGListAdapterDataSource func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { return data as! [IGListDiffable] } func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { if object is Int { return HorizontalSectionController() } return LabelSectionController() } func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil } }
bsd-3-clause
0063c499c22f106894bc4ee79ae10612
31.4
113
0.688984
5.586207
false
false
false
false
marcusellison/lil-twitter
lil-twitter/ComposeViewController.swift
1
2280
// // ComposeViewController.swift // lil-twitter // // Created by Marcus J. Ellison on 5/22/15. // Copyright (c) 2015 Marcus J. Ellison. All rights reserved. // import UIKit //@objc protocol ComposeViewControllerDelegate { // optional func composeViewController(composeViewController: ComposeViewController, didPostNewTweet tweet: Tweet) //} class ComposeViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var screennameLabel: UILabel! @IBOutlet weak var thumbLabel: UIImageView! @IBOutlet weak var tweetField: UITextField! // weak var delegate: ComposeViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() var imageURL = NSURL(string: User.currentUser!.profileImageURL!) nameLabel.text = User.currentUser?.name screennameLabel.text = User.currentUser?.screenname thumbLabel.setImageWithURL(imageURL) self.navigationItem.title = "140" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func postTweet(sender: AnyObject) { println("posting tweet") var tweetText = tweetField.text TwitterClient.sharedInstance.postTweet(tweetField.text) { (tweet, error) -> () in //used if segue transition is modal: self.dismissViewControllerAnimated(true, completion: nil) // self.delegate?.composeViewController!(self, didPostNewTweet: tweet!) //used because transition is show self.navigationController?.popViewControllerAnimated(true) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // change text count @IBAction func onCharacterChange(sender: AnyObject) { self.navigationItem.title = "\(140 - count(tweetField.text))" } }
mit
fd9fabd6fa84fbcb357c8129d818b021
31.571429
117
0.675877
5.066667
false
false
false
false
zhangliangzhi/iosStudyBySwift
xxcolor/Pods/SwiftyStoreKit/SwiftyStoreKit/SwiftyStoreKit.swift
2
11716
// // SwiftyStoreKit.swift // SwiftyStoreKit // // Copyright (c) 2015 Andrea Bizzotto ([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 StoreKit public class SwiftyStoreKit { private let productsInfoController: ProductsInfoController private let paymentQueueController: PaymentQueueController private var receiptRefreshRequest: InAppReceiptRefreshRequest? init(productsInfoController: ProductsInfoController = ProductsInfoController(), paymentQueueController: PaymentQueueController = PaymentQueueController(paymentQueue: SKPaymentQueue.default())) { self.productsInfoController = productsInfoController self.paymentQueueController = paymentQueueController } // MARK: Internal methods func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) { return productsInfoController.retrieveProductsInfo(productIds, completion: completion) } func purchaseProduct(_ productId: String, atomically: Bool = true, applicationUsername: String = "", completion: @escaping ( PurchaseResult) -> Void) { if let product = productsInfoController.products[productId] { purchase(product: product, atomically: atomically, applicationUsername: applicationUsername, completion: completion) } else { retrieveProductsInfo(Set([productId])) { result -> Void in if let product = result.retrievedProducts.first { self.purchase(product: product, atomically: atomically, applicationUsername: applicationUsername, completion: completion) } else if let error = result.error { completion(.error(error: SKError(_nsError: error as NSError))) } else if let invalidProductId = result.invalidProductIDs.first { let userInfo = [ NSLocalizedDescriptionKey: "Invalid product id: \(invalidProductId)" ] let error = NSError(domain: SKErrorDomain, code: SKError.paymentInvalid.rawValue, userInfo: userInfo) completion(.error(error: SKError(_nsError: error))) } } } } func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) { paymentQueueController.restorePurchases(RestorePurchases(atomically: atomically, applicationUsername: applicationUsername) { results in let results = self.processRestoreResults(results) completion(results) }) } func completeTransactions(atomically: Bool = true, completion: @escaping ([Product]) -> Void) { paymentQueueController.completeTransactions(CompleteTransactions(atomically: atomically, callback: completion)) } func finishTransaction(_ transaction: PaymentTransaction) { paymentQueueController.finishTransaction(transaction) } func refreshReceipt(_ receiptProperties: [String : Any]? = nil, completion: @escaping (RefreshReceiptResult) -> Void) { receiptRefreshRequest = InAppReceiptRefreshRequest.refresh(receiptProperties) { result in self.receiptRefreshRequest = nil switch result { case .success: if let appStoreReceiptData = InAppReceipt.appStoreReceiptData { completion(.success(receiptData: appStoreReceiptData)) } else { completion(.error(error: ReceiptError.noReceiptData)) } case .error(let e): completion(.error(error: e)) } } } // MARK: private methods private func purchase(product: SKProduct, atomically: Bool, applicationUsername: String = "", completion: @escaping (PurchaseResult) -> Void) { guard SwiftyStoreKit.canMakePayments else { let error = NSError(domain: SKErrorDomain, code: SKError.paymentNotAllowed.rawValue, userInfo: nil) completion(.error(error: SKError(_nsError: error))) return } paymentQueueController.startPayment(Payment(product: product, atomically: atomically, applicationUsername: applicationUsername) { result in completion(self.processPurchaseResult(result)) }) } private func processPurchaseResult(_ result: TransactionResult) -> PurchaseResult { switch result { case .purchased(let product): return .success(product: product) case .failed(let error): return .error(error: error) case .restored(let product): return .error(error: storeInternalError(description: "Cannot restore product \(product.productId) from purchase path")) } } private func processRestoreResults(_ results: [TransactionResult]) -> RestoreResults { var restoredProducts: [Product] = [] var restoreFailedProducts: [(SKError, String?)] = [] for result in results { switch result { case .purchased(let product): let error = storeInternalError(description: "Cannot purchase product \(product.productId) from restore purchases path") restoreFailedProducts.append((error, product.productId)) case .failed(let error): restoreFailedProducts.append((error, nil)) case .restored(let product): restoredProducts.append(product) } } return RestoreResults(restoredProducts: restoredProducts, restoreFailedProducts: restoreFailedProducts) } private func storeInternalError(code: SKError.Code = SKError.unknown, description: String = "") -> SKError { let error = NSError(domain: SKErrorDomain, code: code.rawValue, userInfo: [ NSLocalizedDescriptionKey: description ]) return SKError(_nsError: error) } } extension SwiftyStoreKit { // MARK: Singleton private static let sharedInstance = SwiftyStoreKit() // MARK: Public methods - Purchases public class var canMakePayments: Bool { return SKPaymentQueue.canMakePayments() } public class func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) { return sharedInstance.retrieveProductsInfo(productIds, completion: completion) } /** * Purchase a product * - Parameter productId: productId as specified in iTunes Connect * - Parameter atomically: whether the product is purchased atomically (e.g. finishTransaction is called immediately) * - Parameter applicationUsername: an opaque identifier for the user’s account on your system * - Parameter completion: handler for result */ public class func purchaseProduct(_ productId: String, atomically: Bool = true, applicationUsername: String = "", completion: @escaping ( PurchaseResult) -> Void) { sharedInstance.purchaseProduct(productId, atomically: atomically, applicationUsername: applicationUsername, completion: completion) } public class func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) { sharedInstance.restorePurchases(atomically: atomically, applicationUsername: applicationUsername, completion: completion) } public class func completeTransactions(atomically: Bool = true, completion: @escaping ([Product]) -> Void) { sharedInstance.completeTransactions(atomically: atomically, completion: completion) } public class func finishTransaction(_ transaction: PaymentTransaction) { sharedInstance.finishTransaction(transaction) } // After verifying receive and have `ReceiptError.NoReceiptData`, refresh receipt using this method public class func refreshReceipt(_ receiptProperties: [String : Any]? = nil, completion: @escaping (RefreshReceiptResult) -> Void) { sharedInstance.refreshReceipt(receiptProperties, completion: completion) } } extension SwiftyStoreKit { // MARK: Public methods - Receipt verification /** * Return receipt data from the application bundle. This is read from Bundle.main.appStoreReceiptURL */ public static var localReceiptData: Data? { return InAppReceipt.appStoreReceiptData } /** * Verify application receipt * - Parameter password: Only used for receipts that contain auto-renewable subscriptions. Your app’s shared secret (a hexadecimal string). * - Parameter session: the session used to make remote call. * - Parameter completion: handler for result */ public class func verifyReceipt( using validator: ReceiptValidator, password: String? = nil, completion:@escaping (VerifyReceiptResult) -> Void) { InAppReceipt.verify(using: validator, password: password) { result in DispatchQueue.main.async { completion(result) } } } /** * Verify the purchase of a Consumable or NonConsumable product in a receipt * - Parameter productId: the product id of the purchase to verify * - Parameter inReceipt: the receipt to use for looking up the purchase * - return: either notPurchased or purchased */ public class func verifyPurchase( productId: String, inReceipt receipt: ReceiptInfo ) -> VerifyPurchaseResult { return InAppReceipt.verifyPurchase(productId: productId, inReceipt: receipt) } /** * Verify the purchase of a subscription (auto-renewable, free or non-renewing) in a receipt. This method extracts all transactions mathing the given productId and sorts them by date in descending order, then compares the first transaction expiry date against the validUntil value. * - Parameter productId: the product id of the purchase to verify * - Parameter inReceipt: the receipt to use for looking up the subscription * - Parameter validUntil: date to check against the expiry date of the subscription. If nil, no verification * - Parameter validDuration: the duration of the subscription. Only required for non-renewable subscription. * - return: either NotPurchased or Purchased / Expired with the expiry date found in the receipt */ public class func verifySubscription( type: SubscriptionType, productId: String, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date() ) -> VerifySubscriptionResult { return InAppReceipt.verifySubscription(type: type, productId: productId, inReceipt: receipt, validUntil: date) } }
mit
869048d29fd1eafe6e51588be56d0d7c
44.046154
286
0.695611
5.483146
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/Models/ActionSheetAction.swift
1
1071
// // ActionSheetAction.swift // Parse Dashboard for iOS // // Created by Nathan Tannar on 5/1/18. // Copyright © 2018 Nathan Tannar. All rights reserved. // import IGListKit final class ActionSheetAction: ListDiffable { typealias ActionSelectionCallback = (AnyObject?)->Void // MARK: - Properties var title: String var image: UIImage? var callback: ActionSelectionCallback? var style: UIAlertActionStyle // MARK: - Initialization init(title: String, image: UIImage? = nil, style: UIAlertActionStyle, callback: ActionSelectionCallback?) { self.title = title self.image = image self.style = style self.callback = callback } // MARK: - ListDiffable func diffIdentifier() -> NSObjectProtocol { return title as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { guard let action = object as? ActionSheetAction else { return false } return action.title == title } }
mit
20be17f3f5b1747ae2eb34006b5a692e
22.777778
111
0.636449
4.953704
false
false
false
false
enpitut/SAWARITAI
iOS/PoiPet/DayViewController.swift
1
7405
// // DayViewController.swift // PoiPet // // Created by koooootake on 2015/11/15. // Copyright © 2015年 koooootake. All rights reserved. // import UIKit class DayViewController: UIViewController,NSXMLParserDelegate,UITableViewDelegate, UITableViewDataSource { let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate @IBOutlet weak var DayTableView: UITableView! @IBOutlet weak var poikunView: UIView! @IBOutlet weak var poikunLabel: UILabel! var pois:[PoiModel] = [PoiModel]() override func viewDidLoad() { super.viewDidLoad() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MM月dd日"; print("SELECT:\(dateFormatter.stringFromDate(appDelegate.selectDay!))") switch appDelegate.poiWeek!{ case 0: self.title = "\(dateFormatter.stringFromDate(appDelegate.selectDay!)) 日曜日" poikunView.backgroundColor = UIColor(red: 217/255.0, green: 150/255.0, blue: 148/255.0, alpha: 1.0) case 1: self.title = "\(dateFormatter.stringFromDate(appDelegate.selectDay!)) 月曜日" poikunView.backgroundColor = UIColor(red: 85/255.0, green: 142/255.0, blue: 213/255.0, alpha: 1.0) case 2: self.title = "\(dateFormatter.stringFromDate(appDelegate.selectDay!)) 火曜日" poikunView.backgroundColor = UIColor(red: 85/255.0, green: 142/255.0, blue: 213/255.0, alpha: 1.0) case 3: self.title = "\(dateFormatter.stringFromDate(appDelegate.selectDay!)) 水曜日" poikunView.backgroundColor = UIColor(red: 85/255.0, green: 142/255.0, blue: 213/255.0, alpha: 1.0) case 4: self.title = "\(dateFormatter.stringFromDate(appDelegate.selectDay!)) 木曜日" poikunView.backgroundColor = UIColor(red: 85/255.0, green: 142/255.0, blue: 213/255.0, alpha: 1.0) case 5: self.title = "\(dateFormatter.stringFromDate(appDelegate.selectDay!)) 金曜日" poikunView.backgroundColor = UIColor(red: 85/255.0, green: 142/255.0, blue: 213/255.0, alpha: 1.0) case 6: self.title = "\(dateFormatter.stringFromDate(appDelegate.selectDay!)) 土曜日" poikunView.backgroundColor = UIColor(red: 155/255.0, green: 187/255.0, blue: 89/255.0, alpha: 1.0) case 7: self.title = "\(dateFormatter.stringFromDate(appDelegate.selectDay!)) 今日" poikunView.backgroundColor = UIColor(red: 247.0/255.0, green: 150.0/255.0, blue: 70.0/255.0, alpha: 1.0) default: break } poikunLabel.text = "\(appDelegate.poiTime.count) Poi Thank You!" DayTableView.delegate = self DayTableView.dataSource = self setDay() } class Poi { var id:String! var date:String! var month:String! var year:String! var time:String! var location:String! var cap:String! var bottle:String! var label:String! var poipetID:String! } func setDay(){ for var i:Int = 0 ; i < appDelegate.poiTime.count ; i++ { var poi:PoiModel //キャップがはずれているか if Int(appDelegate.poiCap[i]) == 1 && Int(appDelegate.poiBottle[i])==1 && Int(appDelegate.poiLabel[i])==1{ switch Int(appDelegate.poipetID[i])!{ case 1: poi = PoiModel(time: "\(appDelegate.poiTime[i])", place: "\(appDelegate.poiPlace[i])" , color: UIColor(red: 217/255.0, green: 150/255.0, blue: 148/255.0, alpha: 1.0), image:UIImage(named: "petHart.png")!)//ぴんく case 2: poi = PoiModel(time: "\(appDelegate.poiTime[i])", place: "\(appDelegate.poiPlace[i])" , color: UIColor(red: 155/255.0, green: 187/255.0, blue: 89/255.0, alpha: 1.0), image:UIImage(named: "petHart.png")!)//みどり default: poi = PoiModel(time: "\(appDelegate.poiTime[i])", place: "\(appDelegate.poiPlace[i])" , color: UIColor(red: 247.0/255.0, green: 150.0/255.0, blue: 70.0/255.0, alpha: 1.0), image:UIImage(named: "petHart.png")!)//オレンジ break } }else{ switch Int(appDelegate.poipetID[i])!{ case 1: poi = PoiModel(time: "\(appDelegate.poiTime[i])", place: "\(appDelegate.poiPlace[i])" , color: UIColor(red: 217/255.0, green: 150/255.0, blue: 148/255.0, alpha: 1.0), image:UIImage(named: "pet.png")!)//ぴんく case 2: poi = PoiModel(time: "\(appDelegate.poiTime[i])", place: "\(appDelegate.poiPlace[i])" , color: UIColor(red: 155/255.0, green: 187/255.0, blue: 89/255.0, alpha: 1.0), image:UIImage(named: "pet.png")!)//みどり default: poi = PoiModel(time: "\(appDelegate.poiTime[i])", place: "\(appDelegate.poiPlace[i])" , color: UIColor(red: 247.0/255.0, green: 150.0/255.0, blue: 70.0/255.0, alpha: 1.0), image:UIImage(named: "pet.png")!)//オレンジ break } } pois.append(poi) } appDelegate.poiTime = [] appDelegate.poiPlace = [] appDelegate.poiCap = [] appDelegate.poiBottle = [] appDelegate.poiLabel = [] appDelegate.poipetID = [] } // セクション数 func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } // セクションの行数 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return pois.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell { let cell: DayTableViewCell = tableView.dequeueReusableCellWithIdentifier("DayTableViewCell", forIndexPath: indexPath) as! DayTableViewCell cell.setCell(pois[indexPath.row]) return cell } override func viewWillDisappear(animated: Bool) { //ナビゲーションバー色 self.navigationController!.navigationBar.barTintColor = UIColor(red: 247.0/255.0, green: 150.0/255.0, blue: 70.0/255.0, alpha: 1.0)//オレンジ } override func viewWillAppear(animated: Bool) { //ナビゲーションバー色 self.navigationController!.navigationBar.barTintColor = UIColor(red: 85/255.0, green: 142/255.0, blue: 213/255.0, alpha: 1.0)//あお switch appDelegate.poiWeek!{ case 0: self.navigationController!.navigationBar.barTintColor = UIColor(red: 217/255.0, green: 150/255.0, blue: 148/255.0, alpha: 1.0)//ピンク case 6: self.navigationController!.navigationBar.barTintColor = UIColor(red: 155/255.0, green: 187/255.0, blue: 89/255.0, alpha: 1.0)//みどり case 7: self.navigationController!.navigationBar.barTintColor = UIColor(red: 247.0/255.0, green: 150.0/255.0, blue: 70.0/255.0, alpha: 1.0)//オレンジ default: break } } }
gpl-2.0
1678da553e0c752bcf9167267bcc3a98
41.532544
235
0.584307
3.977864
false
false
false
false
FrostDigital/AWSTest-iOS
AWSTest/AppDelegate.swift
1
7705
// // AppDelegate.swift // AWSTest // // Created by Sergii Nezdolii on 17/12/15. // Copyright © 2015 FrostDigital. All rights reserved. // import UIKit import AWSSNS @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let notificationSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Badge, UIUserNotificationType.Sound, UIUserNotificationType.Alert], categories: nil) UIApplication.sharedApplication().registerForRemoteNotifications() UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) // Sets up the AWS Mobile SDK for iOS let credentialsProvider = AWSCognitoCredentialsProvider( regionType: CognitoRegionType, identityPoolId: CognitoIdentityPoolId) let defaultServiceConfiguration = AWSServiceConfiguration( region: DefaultServiceRegionType, credentialsProvider: credentialsProvider) AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = defaultServiceConfiguration 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 application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) { let deviceTokenString = "\(deviceToken)" .stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString:"<>")) .stringByReplacingOccurrencesOfString(" ", withString: "") print("deviceTokenString: \(deviceTokenString)") NSUserDefaults.standardUserDefaults().setObject(deviceTokenString, forKey: kDeviceToken) self.mainViewController()?.displayDeviceInfo() self.registerForSNSWithDeviceToken(deviceTokenString) } func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) { print("Failed to register with error: \(error)") } func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print("userInfo: \(userInfo)") } func mainViewController() -> ViewController? { let rootViewController = self.window!.rootViewController if rootViewController is ViewController { return rootViewController as! ViewController? } if rootViewController?.childViewControllers.first is ViewController { return rootViewController?.childViewControllers.first as! ViewController? } return nil } //MARK: Amazon SNS related methods func registerForSNSWithDeviceToken(deviceToken: String) { let sns = AWSSNS.defaultSNS() let request = AWSSNSCreatePlatformEndpointInput() request.token = deviceToken request.platformApplicationArn = SNSPlatformApplicationArn sns.createPlatformEndpoint(request).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task: AWSTask!) -> AnyObject! in if task.error != nil { print("Error: \(task.error)") } else { let createEndpointResponse = task.result as! AWSSNSCreateEndpointResponse print("endpointArn: \(createEndpointResponse.endpointArn)") NSUserDefaults.standardUserDefaults().setObject(createEndpointResponse.endpointArn, forKey: kEndpointArn) self.mainViewController()?.displayDeviceInfo() self.enableEndpointWithARN(createEndpointResponse.endpointArn) } return nil }) } func enableEndpointWithARN(endpointArn: String?) { let sns = AWSSNS.defaultSNS() let request = AWSSNSSetEndpointAttributesInput() request.attributes = ["Enabled":"true"] request.endpointArn = endpointArn sns.setEndpointAttributes(request).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task: AWSTask!) -> AnyObject! in if task.error != nil { print("Error: \(task.error)") } else { //Do nothing for now } return nil }) } //MARK: Amazon SNS Topic Subscription methods func subscribeToTopic(topicArn: String!) { let sns = AWSSNS.defaultSNS() let request = AWSSNSSubscribeInput() request.endpoint = NSUserDefaults.standardUserDefaults().stringForKey(kEndpointArn) request.topicArn = topicArn request.protocols = "application" sns.subscribe(request).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task: AWSTask!) -> AnyObject! in if task.error != nil { print("Error: \(task.error)") } else { NSUserDefaults.standardUserDefaults().setObject((task.result as! AWSSNSSubscribeResponse).subscriptionArn, forKey: topicArn) self.mainViewController()?.updateTopicsUI() } return nil }) } func unsubscribeFromTopic(topicArn: String!) { let sns = AWSSNS.defaultSNS() let request = AWSSNSUnsubscribeInput() request.subscriptionArn = NSUserDefaults.standardUserDefaults().stringForKey(topicArn) sns.unsubscribe(request).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: { (task: AWSTask!) -> AnyObject! in if task.error != nil { print("Error: \(task.error)") } else { NSUserDefaults.standardUserDefaults().removeObjectForKey(topicArn) self.mainViewController()?.updateTopicsUI() } return nil }) } }
mit
cdc27fbbe19f79ab8e5dd4701fdc650a
45.690909
285
0.679258
6.056604
false
false
false
false
sarfraz-akhtar01/SPCalendar
SPCalendar/Classes/CVCalendarMonthView.swift
1
7076
// // CVCalendarMonthView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public final class CVCalendarMonthView: UIView { // MARK: - Non public properties fileprivate var interactiveView: UIView! public override var frame: CGRect { didSet { if let calendarView = calendarView { if calendarView.calendarMode == CalendarMode.monthView { updateInteractiveView() } } } } fileprivate var touchController: CVCalendarTouchController { return calendarView.touchController } var allowScrollToPreviousMonth = true // MARK: - Public properties public weak var calendarView: CVCalendarView! public var date: Foundation.Date! public var numberOfWeeks: Int! public var weekViews: [CVCalendarWeekView]! public var weeksIn: [[Int : [Int]]]? public var weeksOut: [[Int : [Int]]]? public var currentDay: Int? public var potentialSize: CGSize { return CGSize(width: bounds.width, height: CGFloat(weekViews.count) * weekViews[0].bounds.height + calendarView.appearance.spaceBetweenWeekViews! * CGFloat(weekViews.count)) } // MARK: - Initialization public init(calendarView: CVCalendarView, date: Foundation.Date) { super.init(frame: CGRect.zero) self.calendarView = calendarView self.date = date commonInit() } public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func mapDayViews(_ body: (DayView) -> Void) { for weekView in self.weekViews { for dayView in weekView.dayViews { body(dayView) } } } } // MARK: - Creation and destruction extension CVCalendarMonthView { public func commonInit() { let calendarManager = calendarView.manager safeExecuteBlock({ let calendar = self.calendarView.delegate?.calendar?() ?? Calendar.current self.numberOfWeeks = calendarManager?.monthDateRange(self.date).countOfWeeks self.weeksIn = calendarManager?.weeksWithWeekdaysForMonthDate(self.date).weeksIn self.weeksOut = calendarManager?.weeksWithWeekdaysForMonthDate(self.date).weeksOut self.currentDay = Manager.dateRange(calendarView.selectedDate, calendar: calendar).day }, collapsingOnNil: true, withObjects: date as AnyObject?) } } // MARK: Content reload extension CVCalendarMonthView { public func reloadViewsWithRect(_ frame: CGRect) { self.frame = frame safeExecuteBlock({ for (index, weekView) in self.weekViews.enumerated() { if let size = self.calendarView.weekViewSize { weekView.frame = CGRect(x: 0, y: size.height * CGFloat(index), width: size.width, height: size.height) weekView.reloadDayViews() } } }, collapsingOnNil: true, withObjects: weekViews as AnyObject?) } } // MARK: - Content fill & update extension CVCalendarMonthView { public func updateAppearance(_ frame: CGRect) { self.frame = frame createWeekViews() } public func createWeekViews() { weekViews = [CVCalendarWeekView]() safeExecuteBlock({ for i in 0..<self.numberOfWeeks! { let weekView = CVCalendarWeekView(monthView: self, index: i) self.safeExecuteBlock({ self.weekViews!.append(weekView) }, collapsingOnNil: true, withObjects: self.weekViews as AnyObject?) self.addSubview(weekView) } }, collapsingOnNil: true, withObjects: numberOfWeeks as AnyObject?) } } // MARK: - Interactive view management & update extension CVCalendarMonthView { public func updateInteractiveView() { safeExecuteBlock({ let mode = self.calendarView!.calendarMode! if mode == .monthView { if let interactiveView = self.interactiveView { interactiveView.frame = self.bounds interactiveView.removeFromSuperview() self.addSubview(interactiveView) } else { self.interactiveView = UIView(frame: self.bounds) self.interactiveView.backgroundColor = .clear let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(CVCalendarMonthView.didTouchInteractiveView(_:))) let pressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(CVCalendarMonthView.didPressInteractiveView(_:))) pressRecognizer.minimumPressDuration = 0.3 self.interactiveView.addGestureRecognizer(pressRecognizer) self.interactiveView.addGestureRecognizer(tapRecognizer) self.addSubview(self.interactiveView) } } }, collapsingOnNil: false, withObjects: calendarView) } public func didPressInteractiveView(_ recognizer: UILongPressGestureRecognizer) { let location = recognizer.location(in: self.interactiveView) let state: UIGestureRecognizerState = recognizer.state switch state { case .began: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .range(.started)) case .changed: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .range(.changed)) case .ended: touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .range(.ended)) default: break } } public func didTouchInteractiveView(_ recognizer: UITapGestureRecognizer) { let location = recognizer.location(in: self.interactiveView) touchController.receiveTouchLocation(location, inMonthView: self, withSelectionType: .single) } } // MARK: - Safe execution extension CVCalendarMonthView { public 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
08c153c364423248d8ba47856d9e8f30
33.183575
98
0.595676
5.781046
false
false
false
false
rbaladron/SwiftProgramaParaiOS
Ejercicios/MasFeliz/MasFeliz/MyPlayground.playground/Contents.swift
1
332
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //variables y constantes var nombre = "David" let edad = 40 //Arrays var deportes = ["Fútbol"] deportes.append("Natación") deportes.append("Rugby") deportes[2] //Opcionales var apellido : String? = "García" apellido = nil
mit
8d7795f69ddcafe342247384c13daf08
12.16
52
0.699088
2.741667
false
false
false
false
nekrich/GlobalMessageService-iOS
Source/Core/GMSUser.swift
1
3539
// // GlobalMessageServicesSubscriber.swift // GlobalMessageServices // // Created by Vitalii Budnik on 12/10/15. // Copyright © 2015 Global Message Services Worldwide. All rights reserved. // import Foundation /** Stores subscriber's e-mail & phone */ internal struct GlobalMessageServicesSubscriber { /// Subscriber's e-mail var email: String? /// Subscriber's phone number var phone: Int64? /// Subscriber's registration date var registrationDate: NSDate? // swiftlint:disable valid_docs /** Initializes new subscriber with passed e-mail and phone - parameter email: `String` containig subscriber's e-mail - parameter phone: `Int64` containig subscriber's phone - returns: initialized instance */ init(withEmail email: String?, phone: Int64?, registrationDate: NSDate? = .None) { // swiftlint:enable valid_docs self.email = email self.phone = phone self.registrationDate = registrationDate } // swiftlint:disable valid_docs /** Initializes new subscriber with passed dictionary - parameter dictionary: `[String: AnyObject]` containig subscriber's information `["email": "SomeEmail", "phone": 380XXXXXXXXX]`. Can be `nil` - returns: initialized instance, or `nil`, if no dictionary passed */ init?(withDictionary dictionary: [String: AnyObject]?) { // swiftlint:enable valid_docs if let dictionary = dictionary { //guard let email = dictionary["email"] as? String, // phone = dictionary["phone"] as? String else { return nil } email = dictionary["email"] as? String let phone: Int64? if let _phone = Int64(dictionary["phone"] as? String ?? "0") { phone = _phone != 0 ? _phone : .None } else { phone = .None } self.phone = phone if let registrationDate = dictionary["registrationDate"] as? NSNumber { self.registrationDate = NSDate(timeIntervalSinceReferenceDate: registrationDate.doubleValue) } else if let registrationDate = dictionary["registrationDate"] as? Double { self.registrationDate = NSDate(timeIntervalSinceReferenceDate: registrationDate) } else { self.registrationDate = .None } } else { return nil } } } // MARK: DictionaryConvertible internal extension GlobalMessageServicesSubscriber { /** Converts current subscriber `struct` to dictionary `[String : AnyObject]` with subscribers e-mail and phone - returns: `[String : AnyObject]` dictionary with subscribers e-mail and phone */ func asDictionary() -> [String : AnyObject] { var result = [String: AnyObject]() if let email = email { result["email"] = email } if let phone = phone { result["phone"] = "\(phone)" } if let registrationDate = registrationDate { result["registrationDate"] = NSNumber(double: registrationDate.timeIntervalSinceReferenceDate) } return result } } // MARK: CutomStringConvertible extension GlobalMessageServicesSubscriber: Equatable {} /** Compares two instances of `GlobalMessageServicesSubscriber` - Parameter lhs: first `GlobalMessageServicesSubscriber` instance to compare - Parameter rhs: second `GlobalMessageServicesSubscriber` instance to compare - Returns: `true` if subscribers have equal phone numbers and e-mails, `false` otherwise */ internal func == (lhs: GlobalMessageServicesSubscriber, rhs: GlobalMessageServicesSubscriber) -> Bool { return lhs.email == rhs.email && lhs.phone == rhs.phone && lhs.registrationDate == rhs.registrationDate }
apache-2.0
4982d342973e49619c16cc18ffba715e
30.873874
110
0.698982
4.547558
false
false
false
false
zhangjk4859/NextStep
代码实现/测试区域/基本语法/基本语法/main.swift
1
16692
// // main.swift // 基本语法 // // Created by 张俊凯 on 2017/1/12. // Copyright © 2017年 张俊凯. All rights reserved. // import Cocoa // 定义一个交换两个变量的函数 func swapTwoValues<T>(_ a: inout T, _ b: inout T) { let temporaryA = a a = b b = temporaryA } var numb1 = 100 var numb2 = 200 print("交换前数据: \(numb1) 和 \(numb2)") swapTwoValues(&numb1, &numb2) print("交换后数据: \(numb1) 和 \(numb2)") var str1 = "A" var str2 = "B" print("交换前数据: \(str1) 和 \(str2)") swapTwoValues(&str1, &str2) print("交换后数据: \(str1) 和 \(str2)") //func swapTwoStrings(_ a: inout String, _ b: inout String) { // let temporaryA = a // a = b // b = temporaryA //} // //func swapTwoDoubles(_ a: inout Double, _ b: inout Double) { // let temporaryA = a // a = b // b = temporaryA //} // 定义一个交换两个变量的函数 //func swapTwoInts(_ a: inout Int, _ b: inout Int) { // let temporaryA = a // a = b // b = temporaryA //} // //var numb1 = 100 //var numb2 = 200 // //print("交换前数据: \(numb1) 和 \(numb2)") //swapTwoInts(&numb1, &numb2) //print("交换后数据: \(numb1) 和 \(numb2)") //protocol classa { // // var marks: Int { get set } // var result: Bool { get } // // func attendance() -> String // func markssecured() -> String // //} // //protocol classb: classa { // // var present: Bool { get set } // var subject: String { get set } // var stname: String { get set } // //} // //class classc: classb { // var marks = 96 // let result = true // var present = false // var subject = "Swift 协议" // var stname = "Protocols" // // func attendance() -> String { // return "The \(stname) has secured 99% attendance" // } // // func markssecured() -> String { // return "\(stname) has scored \(marks)" // } //} // //let studdet = classc() //studdet.stname = "Swift" //studdet.marks = 98 //studdet.markssecured() // //print(studdet.marks) //print(studdet.result) //print(studdet.present) //print(studdet.subject) //print(studdet.stname) //extension Int { // func topics(summation: () -> ()) { // for _ in 0..<self { // summation() // } // } //} // //4.topics(summation: { // print("扩展模块内") //}) // //3.topics(summation: { // print("内型转换模块内") ////}) //struct sum { // var num1 = 100, num2 = 200 //} // //struct diff { // var no1 = 200, no2 = 100 //} // //struct mult { // var a = sum() // var b = diff() //} // // //extension mult { // init(x: sum, y: diff) { // _ = x.num1 + x.num2 // _ = y.no1 + y.no2 // } //} // // //let a = sum(num1: 100, num2: 200) //let b = diff(no1: 200, no2: 100) // //let getMult = mult(x: a, y: b) //print("getMult sum\(getMult.a.num1, getMult.a.num2)") //print("getMult diff\(getMult.b.no1, getMult.b.no2)") //extension Int { // var add: Int {return self + 100 } // var sub: Int { return self - 10 } // var mul: Int { return self * 10 } // var div: Int { return self / 5 } //} // //let addition = 3.add //print("加法运算后的值:\(addition)") // //let subtraction = 120.sub //print("减法运算后的值:\(subtraction)") // //let multiplication = 39.mul //print("乘法运算后的值:\(multiplication)") // //let division = 55.div //print("除法运算后的值: \(division)") // //let mix = 30.add + 34.sub //print("混合运算结果:\(mix)") //class Subjects { // var physics: String // init(physics: String) { // self.physics = physics // } //} // //class Chemistry: Subjects { // var equations: String // init(physics: String, equations: String) { // self.equations = equations // super.init(physics: physics) // } //} // //class Maths: Subjects { // var formulae: String // init(physics: String, formulae: String) { // self.formulae = formulae // super.init(physics: physics) // } //} // //// [AnyObject] 类型的数组 //let saprint: [AnyObject] = [ // Chemistry(physics: "固体物理", equations: "赫兹"), // Maths(physics: "流体动力学", formulae: "千兆赫"), // Chemistry(physics: "热物理学", equations: "分贝"), // Maths(physics: "天体物理学", formulae: "兆赫"), // Maths(physics: "微分方程", formulae: "余弦级数")] // // //let samplechem = Chemistry(physics: "固体物理", equations: "赫兹") //print("实例物理学是: \(samplechem.physics)") //print("实例方程式: \(samplechem.equations)") // // //let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫") //print("实例物理学是: \(samplemaths.physics)") //print("实例公式是: \(samplemaths.formulae)") // //var chemCount = 0 //var mathsCount = 0 // //for item in saprint { // // 类型转换的条件形式 // if let show = item as? Chemistry { // print("化学主题是: '\(show.physics)', \(show.equations)") // // 强制形式 // } else if let example = item as? Maths { // print("数学主题是: '\(example.physics)', \(example.formulae)") // } //} // //var exampleany = [Any]() //exampleany.append(12) //exampleany.append(3.14159) //exampleany.append("Any 实例") //exampleany.append(Chemistry(physics: "固体物理", equations: "兆赫")) // //for item2 in exampleany { // switch item2 { // case let someInt as Int: // print("整型值为 \(someInt)") // case let someDouble as Double where someDouble > 0: // print("Pi 值为 \(someDouble)") // case let someString as String: // print("\(someString)") // case let phy as Chemistry: // print("主题 '\(phy.physics)', \(phy.equations)") // default: // print("None") // } //} //class Subjects { // var physics: String // init(physics: String) { // self.physics = physics // } //} // //class Chemistry: Subjects { // var equations: String // init(physics: String, equations: String) { // self.equations = equations // super.init(physics: physics) // } //} // //class Maths: Subjects { // var formulae: String // init(physics: String, formulae: String) { // self.formulae = formulae // super.init(physics: physics) // } //} // //let sa = [ // Chemistry(physics: "固体物理", equations: "赫兹"), // Maths(physics: "流体动力学", formulae: "千兆赫"), // Chemistry(physics: "热物理学", equations: "分贝"), // Maths(physics: "天体物理学", formulae: "兆赫"), // Maths(physics: "微分方程", formulae: "余弦级数")] // // //let samplechem = Chemistry(physics: "固体物理", equations: "赫兹") //print("实例物理学是: \(samplechem.physics)") //print("实例方程式: \(samplechem.equations)") // // //let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫") //print("实例物理学是: \(samplemaths.physics)") //print("实例公式是: \(samplemaths.formulae)") // //var chemCount = 0 //var mathsCount = 0 // //for item in sa { // // 类型转换的条件形式 // if let show = item as? Chemistry { // print("化学主题是: '\(show.physics)', \(show.equations)") // // 强制形式 // } else if let example = item as? Maths { // print("数学主题是: '\(example.physics)', \(example.formulae)") // } //} // //// 可以存储Any类型的数组 exampleany //var exampleany = [Any]() // //exampleany.append(12) //exampleany.append(3.14159) //exampleany.append("Any 实例") //exampleany.append(Chemistry(physics: "固体物理", equations: "兆赫")) // //for item2 in exampleany { // switch item2 { // case let someInt as Int: // print("整型值为 \(someInt)") // case let someDouble as Double where someDouble > 0: // print("Pi 值为 \(someDouble)") // case let someString as String: // print("\(someString)") // case let phy as Chemistry: // print("主题 '\(phy.physics)', \(phy.equations)") // default: // print("None") // } //} //class Subjects { // var physics: String // init(physics: String) { // self.physics = physics // } //} // //class Chemistry: Subjects { // var equations: String // init(physics: String, equations: String) { // self.equations = equations // super.init(physics: physics) // } //} // //class Maths: Subjects { // var formulae: String // init(physics: String, formulae: String) { // self.formulae = formulae // super.init(physics: physics) // } //} // //let sa = [ // Chemistry(physics: "固体物理", equations: "赫兹"), // Maths(physics: "流体动力学", formulae: "千兆赫"), // Chemistry(physics: "热物理学", equations: "分贝"), // Maths(physics: "天体物理学", formulae: "兆赫"), // Maths(physics: "微分方程", formulae: "余弦级数")] // // //let samplechem = Chemistry(physics: "固体物理", equations: "赫兹") //print("实例物理学是: \(samplechem.physics)") //print("实例方程式: \(samplechem.equations)") // // //let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫") //print("实例物理学是: \(samplemaths.physics)") //print("实例公式是: \(samplemaths.formulae)") // //var chemCount = 0 //var mathsCount = 0 // //for item in sa {//是化学模式的时候 成立! // // 类型转换的条件形式 // if let show = item as? Chemistry { // print("化学主题是: '\(show.physics)', \(show.equations)") // // 强制形式 // } else if let example = item as? Maths { // print("数学主题是: '\(example.physics)', \(example.formulae)") // } //} //class Subjects { // var physics: String // init(physics: String) { // self.physics = physics // } //} // //class Chemistry: Subjects { // var equations: String // init(physics: String, equations: String) { // self.equations = equations // super.init(physics: physics) // } //} // //class Maths: Subjects { // var formulae: String // init(physics: String, formulae: String) { // self.formulae = formulae // super.init(physics: physics) // } //} // //let sa = [ // Chemistry(physics: "固体物理", equations: "赫兹"), // Maths(physics: "流体动力学", formulae: "千兆赫"), // Chemistry(physics: "热物理学", equations: "分贝"), // Maths(physics: "天体物理学", formulae: "兆赫"), // Maths(physics: "微分方程", formulae: "余弦级数")] // // //let samplechem = Chemistry(physics: "固体物理", equations: "赫兹") //print("实例物理学是: \(samplechem.physics)") //print("实例方程式: \(samplechem.equations)") // // //let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫") //print("实例物理学是: \(samplemaths.physics)") //print("实例公式是: \(samplemaths.formulae)") // //var chemCount = 0 //var mathsCount = 0 //for item in sa { // // 如果是一个 Chemistry 类型的实例,返回 true,相反返回 false。 // if item is Chemistry { // chemCount += 1 // } else if item is Maths { // mathsCount += 1 // } //} // //print("化学科目包含 \(chemCount) 个主题,数学包含 \(mathsCount) 个主题") //class Subjects { // var physics: String // init(physics: String) { // self.physics = physics // } //} // //class Chemistry: Subjects { // var equations: String // init(physics: String, equations: String) { // self.equations = equations // super.init(physics: physics) // } //} // //class Maths: Subjects { // var formulae: String // init(physics: String, formulae: String) { // self.formulae = formulae // super.init(physics: physics) // } //} // //let sa = [ // Chemistry(physics: "固体物理", equations: "赫兹"), // Maths(physics: "流体动力学", formulae: "千兆赫")] // // //let samplechem = Chemistry(physics: "固体物理", equations: "赫兹") //print("实例物理学是: \(samplechem.physics)") //print("实例方程式: \(samplechem.equations)") // // //let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫") //print("实例物理学是: \(samplemaths.physics)") //print("实例公式是: \(samplemaths.formulae)") //class HTMLElement { // // let name: String // let text: String? // // lazy var asHTML: () -> String = { // [unowned self] in // if let text = self.text { // return "<\(self.name)>\(text)</\(self.name)>" // } else { // return "<\(self.name) />" // } // } // // init(name: String, text: String? = nil) { // self.name = name // self.text = text // } // // deinit { // print("\(name) 被析构") // } // //} // ////创建并打印HTMLElement实例 //var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world") //print(paragraph!.asHTML()) // //// HTMLElement实例将会被销毁,并能看到它的析构函数打印出的消息 //paragraph = nil // //class HTMLElement { // // let name: String // let text: String? // // lazy var asHTML: () -> String = { // if let text = self.text { // return "<\(self.name)>\(text)</\(self.name)>" // } else { // return "<\(self.name) />" // } // } // // init(name: String, text: String? = nil) { // self.name = name // self.text = text // } // // deinit { // print("\(name) is being deinitialized") // } // //} // //// 创建实例并打印信息 //var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world") //print(paragraph!.asHTML()) //class Student { // let name: String // var section: Marks? // // init(name: String) { // self.name = name // } // // deinit { print("\(name)") } //} //class Marks { // let marks: Int // unowned let stname: Student // // init(marks: Int, stname: Student) { // self.marks = marks // self.stname = stname // } // // deinit { print("学生的分数为 \(marks)") } //} // //var module: Student? //module = Student(name: "ARC") //module!.section = Marks(marks: 98, stname: module!) //module = nil //class Module { // let name: String // init(name: String) { self.name = name } // var sub: SubModule? // deinit { print("\(name) 主模块") } //} // //class SubModule { // let number: Int // // init(number: Int) { self.number = number } // // weak var topic: Module? // // deinit { print("子模块 topic 数为 \(number)") } //} // //var toc: Module? //var list: SubModule? //toc = Module(name: "ARC") //list = SubModule(number: 4) //toc!.sub = list //list!.topic = toc // //toc = nil //list = nil //class Person { // let name: String // init(name: String) { self.name = name } // var apartment: Apartment? // deinit { print("\(name) 被析构") } //} // //class Apartment { // let number: Int // init(number: Int) { self.number = number } // var tenant: Person? // deinit { print("Apartment #\(number) 被析构") } //} // //// 两个变量都被初始化为nil //var runoob: Person? //var number73: Apartment? // //// 赋值 //runoob = Person(name: "Runoob") //number73 = Apartment(number: 73) // //// 意感叹号是用来展开和访问可选变量 runoob 和 number73 中的实例 //// 循环强引用被创建 //runoob!.apartment = number73 //number73!.tenant = runoob // //// 断开 runoob 和 number73 变量所持有的强引用时,引用计数并不会降为 0,实例也不会被 ARC 销毁 //// 注意,当你把这两个变量设为nil时,没有任何一个析构函数被调用。 //// 强引用循环阻止了Person和Apartment类实例的销毁,并在你的应用程序中造成了内存泄漏 //runoob = nil //number73 = nil //class Person { // let name: String // init(name: String) { // self.name = name // print("\(name) 开始初始化") // } // deinit { // print("\(name) 被析构") // } //} // //// 值会被自动初始化为nil,目前还不会引用到Person类的实例 //var reference1: Person? //var reference2: Person? //var reference3: Person? // //// 创建Person类的新实例 //reference1 = Person(name: "Runoob") // // ////赋值给其他两个变量,该实例又会多出两个强引用 //reference2 = reference1 //reference3 = reference1 // ////断开第一个强引用 //reference1 = nil ////断开第二个强引用 //reference2 = nil ////断开第三个强引用,并调用析构函数 //reference3 = nil
gpl-3.0
c0504ca35f828439af7d17345f0b4f53
21.500756
76
0.566127
3.035926
false
false
false
false
zzgo/v2ex
v2ex/Pods/RAMAnimatedTabBarController/RAMAnimatedTabBarController/RAMBadge/RAMBadge.swift
6
2744
// // RAMBadge.swift // RAMAnimatedTabBarDemo // // Created by Alex K. on 17/12/15. // Copyright © 2015 Ramotion. All rights reserved. // import UIKit open class RAMBadge: UILabel { internal var topConstraint: NSLayoutConstraint? internal var centerXConstraint: NSLayoutConstraint? open class func badge() -> RAMBadge { return RAMBadge.init(frame: CGRect(x: 0, y: 0, width: 18, height: 18)) } override public init(frame: CGRect) { super.init(frame: frame) layer.backgroundColor = UIColor.red.cgColor; layer.cornerRadius = frame.size.width / 2; configureNumberLabel() translatesAutoresizingMaskIntoConstraints = false // constraints createSizeConstraints(frame.size) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // PRAGMA: create internal func createSizeConstraints(_ size: CGSize) { let widthConstraint = NSLayoutConstraint( item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.greaterThanOrEqual, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size.width) self.addConstraint(widthConstraint) let heightConstraint = NSLayoutConstraint( item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: size.height) self.addConstraint(heightConstraint) } fileprivate func configureNumberLabel() { textAlignment = .center font = UIFont.systemFont(ofSize: 13) textColor = UIColor.white } // PRAGMA: helpers open func addBadgeOnView(_ onView:UIView) { onView.addSubview(self) // create constraints topConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: onView, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 3) onView.addConstraint(topConstraint!) centerXConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: onView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 10) onView.addConstraint(centerXConstraint!) } }
mit
50d72a99973df5e4db8fd82db8361492
27.873684
78
0.612104
5.496994
false
false
false
false
moimz/iCoinTicker
iCoinTicker/AppDelegate.swift
1
115978
// // AppDelegate.swift // iCoinTicker // // Created by Arzz on 2017. 6. 3.. // Copyright © 2017 Moimz. All rights reserved. // import Cocoa import Foundation import ServiceManagement import StoreKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate { @IBOutlet weak var aboutWindow: NSWindow! @IBOutlet weak var preferencesWindow: NSWindow! @IBOutlet weak var preferencesToolbar: NSToolbar! @IBOutlet weak var preferencesGeneral: NSView! @IBOutlet weak var preferencesAppearance: NSView! @IBOutlet weak var preferencesCoin: NSView! @IBOutlet weak var preferencesNotification: NSView! @IBOutlet weak var preferencesDonation: NSView! @IBOutlet weak var notificationEditWindow: NSWindow! var preferences: NSUbiquitousKeyValueStore = NSUbiquitousKeyValueStore() struct Coin { let unit: String let name: String let tag: Int let mark: String let marketParams: [String: String] let markets: [Market] init(_ key: String, _ value: NSMutableDictionary) { let appDelegate = NSApplication.shared().delegate as! AppDelegate self.unit = key self.name = value["name"] as! String self.tag = value["tag"] as! Int self.mark = String(Character(UnicodeScalar(Int(value["mark"] as! String, radix: 16)!)!)) let marketParams: [String: String] = value["marketParams"] as! [String: String] self.marketParams = marketParams var markets: [Market] = [] for market in appDelegate.markets { if (marketParams[market.name] != nil) { markets.append(market) } } self.markets = markets } } struct Api { let url: String let first: [String] let last: [String] let change: [String] let isCompare: Bool init(_ data: NSMutableDictionary) { self.url = data["url"] as! String let first: String! = data["first"] as! String self.first = first == nil ? [] : first.characters.split(separator: ".").map{ String($0) } let last: String! = data["last"] as! String self.last = last == nil ? [] : last!.characters.split(separator: ".").map{ String($0) } let change: String! = data["change"] as! String self.change = change == nil ? [] : change.characters.split(separator: ".").map{ String($0) } self.isCompare = first.characters.count > 0 || change.characters.count > 0 } } struct Market { let name: String let display: String let tag: Int let currency: String let isCombination: Bool let isBtcMarket: Bool let api: Api init(_ key: String,_ value: NSMutableDictionary) { self.name = key self.display = value["display"] as? String == nil ? key : value["display"] as! String self.tag = value["tag"] as! Int self.currency = value["currency"] as! String self.isCombination = value["isCombination"] as! Bool self.isBtcMarket = value["isBtcMarket"] as! Bool self.api = Api(value["api"] as! NSMutableDictionary) } func paddingName() -> String { return self.display + "".padding(toLength: Int((20 - self.display.characters.count) / 4), withPad: "\t", startingAt: 0) } } struct NotificationSetting { let coin: Coin let market: Market let currency: Currency let price: Double let rule: String let repeated: Bool let enabled: Bool init(_ value: NSDictionary) { let appDelegate = NSApplication.shared().delegate as! AppDelegate self.coin = appDelegate.getCoin(value["coin"] as! Int)! self.market = appDelegate.getMarket(value["market"] as! Int)! self.currency = appDelegate.getCurrency(value["currency"] as! String)! self.price = value["price"] as! Double self.rule = value["rule"] as! String self.repeated = value["repeated"] as! Bool self.enabled = value["enabled"] as! Bool } func getCost() -> Double { let appDelegate = NSApplication.shared().delegate as! AppDelegate var cost: Double = appDelegate.costs[self.coin.unit]![self.market.name]! if (self.coin.unit != "BTC" && self.market.isBtcMarket == true && self.currency.code != "BTC") { cost = cost * appDelegate.costs["BTC"]![self.market.name]! } return cost * appDelegate.getCurrencyRate(self.market.currency, self.currency.code) } func isSatisfied() -> Bool { if (self.enabled == false) { return false } if (self.rule == ">=" && self.getCost() >= self.price) { return true } if (self.rule == "<=" && self.getCost() <= self.price) { return true } return false } func notify(_ index: Int) { if (self.isSatisfied() == true) { let appDelegate = NSApplication.shared().delegate as! AppDelegate let numberFormatter = NumberFormatter() numberFormatter.format = self.currency.format let price = self.currency.code + " " + numberFormatter.string(from: NSNumber(value: self.getCost()))! appDelegate.showCostNotification(self.coin, price) if (self.repeated == false) { var notifications: [NSDictionary] = appDelegate.getPreferencesNotifactions() let notification: NSMutableDictionary = notifications[index].mutableCopy() as! NSMutableDictionary notification.setValue(false, forKey: "enabled") notifications[index] = notification as NSDictionary appDelegate.setStorage("notifications", notifications) let tableView: NSTableView = appDelegate.preferencesNotification.viewWithTag(10) as! NSTableView let tableViewSelected: IndexSet = tableView.selectedRowIndexes tableView.reloadData() tableView.selectRowIndexes(tableViewSelected, byExtendingSelection: false) } } } } struct Currency { let code: String let tag: Int let mark: String let format: String init(_ key: String, _ value: NSMutableDictionary) { self.code = key self.tag = value["tag"] as! Int self.mark = value["mark"] as! String self.format = value["format"] as! String } } let statusMenu: NSMenu = NSMenu() let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength) var plist: NSMutableDictionary = [:] var markets: [Market] = [] var coins: [Coin] = [] var currencies: [String: Currency] = [:] var costs: [String: [String: Double]] = [:] var costChanges: [String: [String: Double]] = [:] var donations: [String: SKProduct] = [:] var tickerTimer: Timer = Timer() var notificationTimer = Timer() var timer: Timer = Timer() func applicationDidFinishLaunching(_ aNotification: Notification) { self.preferences.synchronize() self.killLauncher() self.initPlist() self.initCosts() self.initWindows() self.initMenus() self.statusItem.menu = self.statusMenu self.updateTicker() self.startTicker() self.updateData() self.timer = Timer.scheduledTimer(timeInterval: Double(self.getPreferencesRefreshInterval()), target: self, selector: #selector(AppDelegate.updateData), userInfo: nil, repeats: true) self.startNotification() Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(AppDelegate.checkUpdate), userInfo: nil, repeats: false) NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.ubiquitousKeyValueStoreDidChange), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: self.preferences) } /** * Kill start at login launcher process * * @return nil */ func killLauncher() { let launcherAppIdentifier = "com.moimz.iCoinTickerLauncher" var launcherAppRunning = false for app in NSWorkspace.shared().runningApplications { if (app.bundleIdentifier == launcherAppIdentifier) { launcherAppRunning = true break } } if (launcherAppRunning == true) { DistributedNotificationCenter.default().post(name: Notification.Name("killme"), object: Bundle.main.bundleIdentifier!) } } /** * check documents coins.plist in documents folder and update coins.plist file. * Init coins and markets from coins.plist * * @return nil */ func initPlist() { let fileName = "coins.plist" let documentsUrl: URL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!).appendingPathComponent(fileName) let bundlePath = Bundle.main.path(forResource: fileName, ofType: nil)! let documentsPlist: NSMutableDictionary? = NSMutableDictionary(contentsOf: documentsUrl) let bundlePlist: NSMutableDictionary = NSMutableDictionary(contentsOfFile: bundlePath)! let documentsUpdated: Date? = documentsPlist == nil ? nil : documentsPlist!["updated"] as? Date let bundleUpdated: Date = bundlePlist["updated"] as! Date if (documentsUpdated == nil || bundleUpdated.compare(documentsUpdated!) == ComparisonResult.orderedDescending) { do { let content = try String(contentsOfFile: bundlePath, encoding: String.Encoding.utf8) try content.write(to: documentsUrl, atomically: false, encoding: String.Encoding.utf8) } catch {} self.plist = bundlePlist } else { self.plist = documentsPlist! } /** * Sorting market by tag * @todo using sorting option */ let markets: [String: NSMutableDictionary] = self.plist["markets"] as! [String: NSMutableDictionary] var marketSorted: [Int: Market] = [:] for (key, value) in markets { let market: Market = Market(key, value) marketSorted[market.tag] = market } for tag in marketSorted.keys.sorted() { let market: Market = marketSorted[tag]! self.markets.append(market) } /** * Sorting coin by tag * @todo using sorting option */ let coins: [String: NSMutableDictionary] = self.plist["coins"] as! [String: NSMutableDictionary] var coinSorted: [Int: Coin] = [:] for (key, value) in coins { let coin: Coin = Coin(key, value) coinSorted[coin.tag] = coin } for tag in coinSorted.keys.sorted() { let coin: Coin = coinSorted[tag]! self.coins.append(coin) } let currencies: [String: NSMutableDictionary] = self.plist["currencies"] as! [String: NSMutableDictionary] for (key, value) in currencies { let currency: Currency = Currency(key, value) self.currencies[key] = currency } } func initCosts() { for coin in self.coins { for market in self.markets { if (self.costs[coin.unit] == nil) { self.costs[coin.unit] = [:] } if (self.costChanges[coin.unit] == nil) { self.costChanges[coin.unit] = [:] } self.costs[coin.unit]!.updateValue(Double(0), forKey: market.name) self.costChanges[coin.unit]!.updateValue(Double(0), forKey: market.name) } } } /** * Init AboutWindow and PreferencesWindow * Localizing and action * * @return nil */ func initWindows() { /** * Init About Window */ let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String let appname: NSTextField! = self.aboutWindow.contentView!.viewWithTag(100) as! NSTextField appname.stringValue = "iCoinTicker v" + version /** * Init Preferences Toolbar */ for item in self.preferencesToolbar.items { item.label = NSLocalizedString("preferences.toolbar." + item.label, comment: "") item.action = #selector(AppDelegate.preferencesViewSelected) } /** * Init Preferences General Panel */ for view in self.preferencesGeneral.subviews { if (view is NSPopUpButton) { let button: NSPopUpButton = view as! NSPopUpButton for menu in button.menu!.items { menu.title = NSLocalizedString("preferences.general." + menu.title, comment: "") } } else if (view is NSButton) { let button: NSButton = view as! NSButton button.title = NSLocalizedString("preferences.general." + button.title, comment: "") } else if (view is NSTextField) { let textField: NSTextField = view as! NSTextField textField.stringValue = NSLocalizedString("preferences.general." + textField.stringValue, comment: "") + (view.tag == 1 ? " : " : "") } } let refreshInterval: NSPopUpButton = self.preferencesGeneral.viewWithTag(10) as! NSPopUpButton refreshInterval.action = #selector(AppDelegate.setPreferencesRefreshInterval) let currency: NSPopUpButton = self.preferencesGeneral.viewWithTag(20) as! NSPopUpButton let currencyDefault: NSMenuItem = NSMenuItem(title: NSLocalizedString("preferences.general.currency.default", comment: ""), action: #selector(AppDelegate.setPreferencesCurrency), keyEquivalent: "") currencyDefault.tag = 0 currency.menu!.addItem(currencyDefault) for (_, value) in self.currencies { if (value.code == "BTC") { continue } let menu: NSMenuItem = NSMenuItem(title: value.mark + " " + value.code, action: #selector(AppDelegate.setPreferencesCurrency), keyEquivalent: "") menu.tag = value.tag menu.image = NSImage(named: value.code) currency.menu!.addItem(menu) } let autoUpdate: NSButton = self.preferencesGeneral.viewWithTag(100) as! NSButton autoUpdate.action = #selector(AppDelegate.setPreferencesAutoUpdate) let autoUpdateSelect: NSPopUpButton = self.preferencesGeneral.viewWithTag(101) as! NSPopUpButton autoUpdateSelect.action = #selector(AppDelegate.setPreferencesAutoUpdate) let autoEnabledCoin: NSButton = self.preferencesGeneral.viewWithTag(102) as! NSButton autoEnabledCoin.action = #selector(AppDelegate.setPreferencesAutoEnabledCoin) let autoEnabledMarket: NSButton = self.preferencesGeneral.viewWithTag(103) as! NSButton autoEnabledMarket.action = #selector(AppDelegate.setPreferencesAutoEnabledMarket) let startAtLogin: NSButton! = self.preferencesGeneral.viewWithTag(1000) as! NSButton startAtLogin.action = #selector(AppDelegate.setPreferencesStartAtLogin) /** * Init Preferences Appearance Panel */ for view in self.preferencesAppearance.subviews { if (view is NSPopUpButton) { let button: NSPopUpButton = view as! NSPopUpButton for menu in button.menu!.items { menu.title = NSLocalizedString("preferences.appearance." + menu.title, comment: "") } } else if (view is NSButton) { let button: NSButton = view as! NSButton button.title = NSLocalizedString("preferences.appearance." + button.title, comment: "") } else if (view is NSTextField) { let textField: NSTextField = view as! NSTextField textField.stringValue = NSLocalizedString("preferences.appearance." + textField.stringValue, comment: "") + (view.tag == 1 ? " : " : "") } } let fontSize: NSPopUpButton! = self.preferencesAppearance.viewWithTag(10) as! NSPopUpButton fontSize.action = #selector(AppDelegate.setPreferencesFontSize) let tickerDisplayedCurrency: NSPopUpButton! = self.preferencesAppearance.viewWithTag(20) as! NSPopUpButton tickerDisplayedCurrency.action = #selector(AppDelegate.setPreferencesTickerDisplayedCurrency) let tickerDisplayedChange: NSButton! = self.preferencesAppearance.viewWithTag(30) as! NSButton tickerDisplayedChange.action = #selector(AppDelegate.setPreferencesTickerDisplayedChange) let menuDisplayedCurrency: NSPopUpButton! = self.preferencesAppearance.viewWithTag(120) as! NSPopUpButton menuDisplayedCurrency.action = #selector(AppDelegate.setPreferencesMenuDisplayedCurrency) let menuDisplayedChange: NSButton! = self.preferencesAppearance.viewWithTag(130) as! NSButton menuDisplayedChange.action = #selector(AppDelegate.setPreferencesMenuDisplayedChange) /** * Init Preferences Coin Panel */ for view in self.preferencesCoin.subviews { if (view is NSButton) { let button: NSButton = view as! NSButton button.title = NSLocalizedString("preferences.coin." + button.title, comment: "") } else if (view is NSTextField) { let textField: NSTextField = view as! NSTextField textField.stringValue = NSLocalizedString("preferences.coin." + textField.stringValue, comment: "") + (view.tag == 1 ? " : " : "") } } let coins: NSTableView = self.preferencesCoin.viewWithTag(10) as! NSTableView coins.tableColumn(withIdentifier: "unit")?.headerCell.title = NSLocalizedString("preferences.coin.coins.header.unit", comment: "") coins.tableColumn(withIdentifier: "name")?.headerCell.title = NSLocalizedString("preferences.coin.coins.header.name", comment: "") coins.delegate = self coins.dataSource = self let markets: NSTableView = self.preferencesCoin.viewWithTag(20) as! NSTableView markets.tableColumn(withIdentifier: "market")?.headerCell.title = NSLocalizedString("preferences.coin.markets.header.market", comment: "") markets.tableColumn(withIdentifier: "currency")?.headerCell.title = NSLocalizedString("preferences.coin.markets.header.currency", comment: "") markets.delegate = self markets.dataSource = self let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY.MM.dd HH:mm:ss" let lastUpdate: NSTextField = self.preferencesCoin.viewWithTag(200) as! NSTextField lastUpdate.stringValue = NSLocalizedString("preferences.coin.lastUpdate", comment:"") + " : " + dateFormatter.string(from: self.plist["updated"] as! Date) let checkUpdate: NSButton = self.preferencesCoin.viewWithTag(300) as! NSButton checkUpdate.action = #selector(AppDelegate.checkUpdate) let loading = NSProgressIndicator(frame: NSRect(x: 58.0, y: 7.0, width: 16.0, height: 16.0)) loading.style = NSProgressIndicatorStyle.spinningStyle loading.controlSize = NSControlSize.small loading.usesThreadedAnimation = false loading.isDisplayedWhenStopped = false checkUpdate.addSubview(loading) /** * Init Preferences Notification Panel */ for view in self.preferencesNotification.subviews { if (view is NSTextField) { let textField: NSTextField = view as! NSTextField textField.stringValue = NSLocalizedString("preferences.notification." + textField.stringValue, comment: "") + (view.tag == 1 ? " : " : "") } } let notifications: NSTableView = self.preferencesNotification.viewWithTag(10) as! NSTableView notifications.tableColumn(withIdentifier: "coin")?.headerCell.title = NSLocalizedString("preferences.notification.coin", comment: "") notifications.tableColumn(withIdentifier: "market")?.headerCell.title = NSLocalizedString("preferences.notification.market", comment: "") notifications.tableColumn(withIdentifier: "rule")?.headerCell.title = NSLocalizedString("preferences.notification.rule", comment: "") notifications.tableColumn(withIdentifier: "status")?.headerCell.title = NSLocalizedString("preferences.notification.status", comment: "") notifications.delegate = self notifications.dataSource = self notifications.doubleAction = #selector(AppDelegate.openNotificationEditSheet) let addButton: NSButton = self.preferencesNotification.viewWithTag(100) as! NSButton addButton.action = #selector(AppDelegate.openNotificationEditSheet) let removeButton: NSButton = self.preferencesNotification.viewWithTag(200) as! NSButton removeButton.action = #selector(AppDelegate.removeNotifications) /** * Init Preferences Donation Panel */ for view in self.preferencesDonation.subviews { if (view is NSButton) { let button: NSButton = view as! NSButton button.title = NSLocalizedString("preferences.donation." + button.title, comment: "") } else if (view is NSTextField) { let textField: NSTextField = view as! NSTextField if (textField.tag == -1) { continue } textField.stringValue = NSLocalizedString("preferences.donation." + textField.stringValue, comment: "") + (view.tag == 1 ? " : " : "") } } let donations: Set<String> = NSSet(array: ["com.moimz.iCoinTicker.donation.tier1", "com.moimz.iCoinTicker.donation.tier2", "com.moimz.iCoinTicker.donation.tier3", "com.moimz.iCoinTicker.donation.tier4"]) as! Set<String> if (SKPaymentQueue.canMakePayments() == true) { let request = SKProductsRequest(productIdentifiers: donations) request.delegate = self request.start() } SKPaymentQueue.default().add(self) for tag in 1...4 { let button: NSButton = self.preferencesDonation.viewWithTag(tag * 10) as! NSButton button.isEnabled = false let loading = NSProgressIndicator(frame: NSRect(x: 58.0, y: 7.0, width: 16.0, height: 16.0)) loading.style = NSProgressIndicatorStyle.spinningStyle loading.controlSize = NSControlSize.small loading.usesThreadedAnimation = false loading.isDisplayedWhenStopped = false button.addSubview(loading) } /** * Init Preferences Notification Panel */ /** * Init Notification Edit Window */ let notificationEditView: NSView = self.notificationEditWindow.contentView! for view in notificationEditView.subviews { if (view is NSPopUpButton) { let button: NSPopUpButton = view as! NSPopUpButton for menu in button.menu!.items { menu.title = NSLocalizedString("notification.edit." + menu.title, comment: "") } } else if (view is NSButton) { let button: NSButton = view as! NSButton button.title = NSLocalizedString("notification.edit." + button.title, comment: "") } else if (view is NSTextField) { let textField: NSTextField = view as! NSTextField if (textField.tag == -1) { continue } textField.stringValue = NSLocalizedString("notification.edit." + textField.stringValue, comment: "") + (view.tag == 1 ? " : " : "") } } let coinButton: NSPopUpButton = notificationEditView.viewWithTag(10) as! NSPopUpButton for coin in self.coins { let menu: NSMenuItem = NSMenuItem() let title = NSMutableAttributedString(string: "") title.append(NSAttributedString(string: coin.mark, attributes: [NSFontAttributeName: NSFont(name: "cryptocoins-icons", size: 12.0)!])) title.append(NSAttributedString(string: " " + coin.unit + " (" + coin.name + ")", attributes: [NSFontAttributeName: NSFont.systemFont(ofSize: 13.0), NSBaselineOffsetAttributeName: -0.5])) menu.attributedTitle = title menu.tag = coin.tag coinButton.menu!.addItem(menu) } coinButton.action = #selector(AppDelegate.setNotificationEditSheet) let marketButton: NSPopUpButton = notificationEditView.viewWithTag(20) as! NSPopUpButton for market in self.markets { let menu: NSMenuItem = NSMenuItem() menu.title = market.name menu.tag = market.tag menu.image = NSImage(named: market.currency) marketButton.menu!.addItem(menu) } marketButton.action = #selector(AppDelegate.setNotificationEditSheet) let currencyButton: NSPopUpButton = notificationEditView.viewWithTag(30) as! NSPopUpButton for (code, currency) in self.currencies { let menu: NSMenuItem = NSMenuItem() menu.title = currency.code + " (" + currency.mark + ")" menu.tag = currency.tag menu.identifier = code currencyButton.menu!.addItem(menu) } currencyButton.action = #selector(AppDelegate.setNotificationEditSheet) let priceInput: NSTextField = notificationEditView.viewWithTag(40) as! NSTextField priceInput.stringValue = "0" let saveButton: NSButton = notificationEditView.viewWithTag(100) as! NSButton saveButton.title = NSLocalizedString("button.save", comment: "") saveButton.action = #selector(AppDelegate.closeNotificationEditSheet) let closeButton: NSButton = notificationEditView.viewWithTag(200) as! NSButton closeButton.title = NSLocalizedString("button.close", comment: "") closeButton.action = #selector(AppDelegate.closeNotificationEditSheet) } func initPreferences() { /** * Init Preferences General */ let refreshInterval: NSPopUpButton = self.preferencesGeneral.viewWithTag(10) as! NSPopUpButton refreshInterval.select(refreshInterval.menu!.item(withTag: self.getPreferencesRefreshInterval())) let currency: NSPopUpButton = self.preferencesGeneral.viewWithTag(20) as! NSPopUpButton currency.select(currency.menu!.item(withTag: self.getPreferencesCurrency())) let autoUpdate: NSButton = self.preferencesGeneral.viewWithTag(100) as! NSButton autoUpdate.state = self.getPreferencesAutoUpdate() == -1 ? NSOffState : NSOnState let autoUpdateSelect: NSPopUpButton = self.preferencesGeneral.viewWithTag(101) as! NSPopUpButton if (self.getPreferencesAutoUpdate() == -1) { autoUpdateSelect.isEnabled = false autoUpdateSelect.select(autoUpdateSelect.menu?.item(withTag: 0)) } else { autoUpdateSelect.isEnabled = true autoUpdateSelect.select(autoUpdateSelect.menu?.item(withTag: self.getPreferencesAutoUpdate())) } let autoEnabledCoin: NSButton = self.preferencesGeneral.viewWithTag(102) as! NSButton autoEnabledCoin.state = self.getPreferencesAutoEnabledCoin() == true ? NSOnState : NSOffState let autoEnabledMarket: NSButton = self.preferencesGeneral.viewWithTag(103) as! NSButton autoEnabledMarket.state = self.getPreferencesAutoEnabledMarket() == true ? NSOnState : NSOffState let startAtLogin: NSButton! = self.preferencesGeneral.viewWithTag(1000) as! NSButton startAtLogin.state = self.getPreferencesStartAtLogin() == true ? NSOnState : NSOffState /** * Init Preferences Appearance */ let fontSize: NSPopUpButton! = self.preferencesAppearance.viewWithTag(10) as! NSPopUpButton fontSize.select(fontSize.menu!.item(withTag: self.getPreferencesFontSize())) let tickerDisplayedCurrency: NSPopUpButton! = self.preferencesAppearance.viewWithTag(20) as! NSPopUpButton tickerDisplayedCurrency.select(tickerDisplayedCurrency.menu!.item(withTag: self.getPreferencesTickerDisplayedCurrency())) let tickerDisplayedChange: NSButton! = self.preferencesAppearance.viewWithTag(30) as! NSButton tickerDisplayedChange.state = self.getPreferencesTickerDisplayedChange() == true ? NSOnState : NSOffState let menuDisplayedCurrency: NSPopUpButton! = self.preferencesAppearance.viewWithTag(120) as! NSPopUpButton menuDisplayedCurrency.select(menuDisplayedCurrency.menu!.item(withTag: self.getPreferencesMenuDisplayedCurrency())) let menuDisplayedChange: NSButton! = self.preferencesAppearance.viewWithTag(130) as! NSButton menuDisplayedChange.state = self.getPreferencesMenuDisplayedChange() == true ? NSOnState : NSOffState /** * Init Preferences Coin */ let coins: NSTableView = self.preferencesCoin.viewWithTag(10) as! NSTableView coins.reloadData() let markets: NSTableView = self.preferencesCoin.viewWithTag(20) as! NSTableView markets.reloadData() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY.MM.dd HH:mm:ss" let lastUpdate: NSTextField = self.preferencesCoin.viewWithTag(200) as! NSTextField lastUpdate.stringValue = NSLocalizedString("preferences.coin.lastUpdate", comment:"") + " : " + dateFormatter.string(from: self.plist["updated"] as! Date) /** * Init Preferences Notification */ let notifications: NSTableView = self.preferencesNotification.viewWithTag(10) as! NSTableView notifications.reloadData() } /** * Init status menu * * @return nil */ func initMenus() { self.stopTicker() self.statusMenu.removeAllItems() let about: NSMenuItem = NSMenuItem(title: NSLocalizedString("menu.about", comment: ""), action: #selector(AppDelegate.openAboutWindow), keyEquivalent: "") self.statusMenu.addItem(about) self.statusMenu.addItem(NSMenuItem.separator()) /** * Init enabled coin menu item */ for coin in self.coins { if (self.isCoinEnabled(coin.unit) == true) { let menu: NSMenuItem = NSMenuItem(title: "", action: nil, keyEquivalent: "") let submenu: NSMenu = NSMenu() menu.tag = coin.tag menu.submenu = submenu let title = NSMutableAttributedString(string: "") title.append(NSAttributedString(string: coin.mark, attributes: [NSFontAttributeName: NSFont(name: "cryptocoins-icons", size: 14.0)!])) title.append(NSAttributedString(string: " " + coin.unit + " (" + coin.name + ")", attributes: [NSFontAttributeName: NSFont.systemFont(ofSize: 14.0), NSBaselineOffsetAttributeName: -0.5])) menu.attributedTitle = title let none: NSMenuItem = NSMenuItem(title: NSLocalizedString("menu.hideTicker", comment: ""), action: #selector(self.setMarketSelectedTag), keyEquivalent: "") none.tag = coin.tag * 1000 none.isEnabled = true submenu.addItem(none) submenu.addItem(NSMenuItem.separator()) var lastSeparator: Bool = true var lastCurrency: String = ""; for market in coin.markets { if (self.isMarketEnabled(market.name) == true) { let menu = NSMenuItem(title: market.paddingName(), action: #selector(self.setMarketSelectedTag), keyEquivalent: "") menu.tag = coin.tag * 1000 + market.tag menu.image = NSImage(named: market.currency) if (lastSeparator == false && lastCurrency != market.currency) { submenu.addItem(NSMenuItem.separator()) } submenu.addItem(menu) if (coin.unit != "BTC" && market.isBtcMarket == true) { let menu = NSMenuItem(title: market.paddingName(), action: #selector(self.setMarketSelectedTag), keyEquivalent: "") menu.tag = coin.tag * 1000 + 100 + market.tag menu.image = NSImage(named: market.currency) submenu.addItem(menu) } lastSeparator = false lastCurrency = market.currency } } let marketSelected: Int = self.getMarketSelectedTag(coin.unit) if (marketSelected % 100 == 0) { menu.state = NSOffState submenu.item(withTag: coin.tag * 1000)!.state = NSOnState } else { menu.state = NSOnState submenu.item(withTag: marketSelected)!.state = NSOnState } self.statusMenu.addItem(menu) } } self.statusMenu.addItem(NSMenuItem.separator()) let refresh: NSMenuItem = NSMenuItem(title: NSLocalizedString("menu.refresh", comment: ""), action: #selector(AppDelegate.refresh), keyEquivalent: "r") refresh.tag = 100000 self.statusMenu.addItem(refresh) self.statusMenu.addItem(NSMenuItem.separator()) let preferences: NSMenuItem = NSMenuItem(title: NSLocalizedString("menu.preferences", comment: ""), action: #selector(AppDelegate.openPreferencesWindow), keyEquivalent: ",") self.statusMenu.addItem(preferences) self.statusMenu.addItem(NSMenuItem.separator()) let quit: NSMenuItem = NSMenuItem(title: NSLocalizedString("menu.quit", comment: ""), action: #selector(AppDelegate.quit), keyEquivalent: "q") self.statusMenu.addItem(quit) } /** * Get coin data by coin unit or tag * * @param Any coin unit or tag * @return Coin? coin */ func getCoin(_ sender: Any) -> Coin? { if (sender is Int) { let tag: Int = sender as! Int for coin in self.coins { if (coin.tag == tag) { return coin } } } else { let unit: String = sender as! String for coin in self.coins { if (coin.unit == unit) { return coin } } } return nil } /** * Get market data by market name or tag * * @param Any market name or tag * @return Market? market */ func getMarket(_ sender: Any) -> Market? { if (sender is Int) { let tag: Int = sender as! Int for market in self.markets { if (market.tag == tag) { return market } } } else { let name: String = sender as! String for market in self.markets { if (market.name == name) { return market } } } return nil } /** * Get currency data * * @param Any currency code or tag * @return Currency currency */ func getCurrency(_ sender: Any) -> Currency? { if (sender is Int) { let tag: Int = sender as! Int for (_, currency) in self.currencies { if (currency.tag == tag) { return currency } } } else { let code: String = sender as! String return self.currencies[code] } return nil } /** * Get ticker market selected tag by coin unit * * @param String coin * @return Int marketSelected */ func getMarketSelectedTag(_ unit: String) -> Int { let coin: Coin = self.getCoin(unit)! let marketSelected = self.getStorage("preferencesMarketSelected") as? NSDictionary if (marketSelected == nil || marketSelected![coin.unit] == nil) { return 0 } else { let marketSelectedTag = marketSelected![coin.unit] as! Int if (self.getMarket(marketSelectedTag % 100) == nil) { return 0 } else { return marketSelectedTag } } } /** * Set selected market * * @param NSMenuItem sender * @return nil */ func setMarketSelectedTag(_ sender: NSMenuItem) { if (sender.state == NSOffState) { let coinTag: Int = sender.tag / 1000 let marketTag: Int = sender.tag % 100 let coin: Coin = self.getCoin(coinTag)! if (marketTag == 0) { self.statusMenu.item(withTag: coinTag)!.state = NSOffState } else { self.statusMenu.item(withTag: coinTag)!.state = NSOnState } for menu in self.statusMenu.item(withTag: coin.tag)!.submenu!.items { if (sender.tag == menu.tag) { menu.state = NSOnState } else { menu.state = NSOffState } } let marketSelected: NSMutableDictionary = self.getStorage("preferencesMarketSelected") as? NSDictionary == nil ? NSMutableDictionary() : (self.getStorage("preferencesMarketSelected") as! NSDictionary).mutableCopy() as! NSMutableDictionary marketSelected.setValue(sender.tag, forKey: coin.unit) self.setStorage("preferencesMarketSelected", marketSelected) self.stopTicker() self.updateTicker() self.startTicker() } } /** * Check coin enabled by coin unit * * @param String coin unit * @return Bool isEnabled */ func isCoinEnabled(_ unit: String) -> Bool { let coin: Coin? = self.getCoin(unit) if (coin == nil) { return false } else { let enabledCoins = self.getStorage("preferencesEnabledCoins") as? NSDictionary if (enabledCoins == nil || enabledCoins![unit] == nil) { let enabledCoins: NSMutableDictionary = self.getStorage("preferencesEnabledCoins") as? NSDictionary == nil ? NSMutableDictionary() : (self.getStorage("preferencesEnabledCoins") as? NSDictionary)?.mutableCopy() as! NSMutableDictionary enabledCoins.setValue(unit == "BTC" || self.getPreferencesAutoEnabledCoin(), forKey: unit) self.setStorage("preferencesEnabledCoins", enabledCoins) return unit == "BTC" || self.getPreferencesAutoEnabledCoin() } return enabledCoins![unit] as! Bool } } /** * Check market enabled by market name * * @param String market name * @return Bool isEnabled */ func isMarketEnabled(_ name: String) -> Bool { let market: Market? = self.getMarket(name) if (market == nil) { return false } else { let enabledMarkets = self.getStorage("preferencesEnabledMarkets") as? NSDictionary if (enabledMarkets == nil || enabledMarkets![name] == nil) { let enabledMarkets: NSMutableDictionary = self.getStorage("preferencesEnabledMarkets") as? NSDictionary == nil ? NSMutableDictionary() : (self.getStorage("preferencesEnabledMarkets") as? NSDictionary)?.mutableCopy() as! NSMutableDictionary enabledMarkets.setValue(name == "Poloniex" || self.getPreferencesAutoEnabledMarket(), forKey: name) self.setStorage("preferencesEnabledMarkets", enabledMarkets) return name == "Poloniex" || self.getPreferencesAutoEnabledMarket() } else { return enabledMarkets![name] as! Bool } } } /** * Get coin cost * * @param String coin unit * @param String market name * @param Bool isBtcRate * @param Bool isTicker * @reutn String cost */ func getCost(_ coin: String, _ market: String, _ isBtcRate: Bool, _ isTicker: Bool) -> String { let coin: Coin = self.getCoin(coin)! let market: Market = self.getMarket(market)! let stored: Double = self.costs[coin.unit]![market.name]! let changed: Double = self.costChanges[coin.unit]![market.name]! var cost: Double = 0 if (coin.unit != "BTC" && market.isBtcMarket == true && isBtcRate == false) { cost = stored * self.costs["BTC"]![market.name]! } else { cost = stored } var currency: Currency if (coin.unit != "BTC" && market.isBtcMarket == true && isBtcRate == true) { currency = self.getCurrency("BTC")! } else { currency = self.getPreferencesCurrency() == 0 ? self.getCurrency(market.currency)! : self.getCurrency(self.getPreferencesCurrency())! } cost = cost * self.getCurrencyRate(market.currency, currency.code) var text: String = "" if (cost == 0) { if (isTicker == true) { return "Loading..." } else { if (self.getPreferencesMenuDisplayedCurrency() == 1) { return currency.mark + " Loading..." } else { return currency.code + " Loading..." } } } else { let numberFormatter = NumberFormatter() numberFormatter.format = currency.format if ((isTicker == true && self.getPreferencesTickerDisplayedCurrency() == 1) || (isTicker == false && self.getPreferencesMenuDisplayedCurrency() == 1)) { text = currency.mark + " " } else if ((isTicker == true && self.getPreferencesTickerDisplayedCurrency() == 2) || isTicker == false) { text = currency.code + " " } text += numberFormatter.string(from: NSNumber(value: cost))! if (isTicker == true && self.getPreferencesTickerDisplayedChange() == true && market.api.isCompare == true) { text += " (" + (changed > 0 ? "+" : "") + String(format:"%0.2f", changed) + "%)" } if (isTicker == false && self.getPreferencesMenuDisplayedChange() == true && market.api.isCompare == true) { text += " (" + (changed > 0 ? "+" : "") + String(format:"%0.2f", changed) + "%)" } return text } } /** * Start ticker timer * * @return nil */ func startTicker() { self.stopTicker() self.tickerTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(AppDelegate.updateTicker), userInfo: nil, repeats: true) } /** * Stop ticker timer * * @return nil */ func stopTicker() { self.tickerTimer.invalidate() } /** * Update ticker string * * @return nil */ func updateTicker() { let tickerString = NSMutableAttributedString(string: "") var markAttributes: [String: Any] = [NSFontAttributeName: NSFont(name: "cryptocoins-icons", size: 14.0)!] var costAttributes: [String: Any] = [NSFontAttributeName: NSFont.systemFont(ofSize: 14.0), NSBaselineOffsetAttributeName: -0.5] if (self.getPreferencesFontSize() == 10) { markAttributes = [NSFontAttributeName: NSFont(name: "cryptocoins-icons", size: 12.0)!] costAttributes = [NSFontAttributeName: NSFont.systemFont(ofSize: 10.0)] } else if (self.getPreferencesFontSize() == 12) { markAttributes = [NSFontAttributeName: NSFont(name: "cryptocoins-icons", size: 12.0)!] costAttributes = [NSFontAttributeName: NSFont.systemFont(ofSize: 12.0), NSBaselineOffsetAttributeName: -0.5] } for coin in self.coins { if (self.isCoinEnabled(coin.unit) == true && self.getMarketSelectedTag(coin.unit) % 100 > 0) { if (tickerString.length > 0) { tickerString.append(NSAttributedString(string: " ", attributes: costAttributes)) } let marketTag: Int = self.getMarketSelectedTag(coin.unit) % 100 let isBtcRate: Bool = self.getMarketSelectedTag(coin.unit) % 1000 > 100 let market: Market = self.getMarket(marketTag)! tickerString.append(NSAttributedString(string: coin.mark, attributes: markAttributes)) tickerString.append(NSAttributedString(string: " " + self.getCost(coin.unit, market.name, isBtcRate, true), attributes: costAttributes)) } } if (tickerString.length == 0) { self.statusItem.image = NSImage(named: "statusIcon") self.statusItem.attributedTitle = nil } else { self.statusItem.image = nil self.statusItem.attributedTitle = tickerString } for coin in self.coins { if (self.isCoinEnabled(coin.unit) == true) { let menu: NSMenuItem? = self.statusMenu.item(withTag: coin.tag) if (menu != nil) { let submenu: NSMenu! = menu!.submenu! for menu in submenu.items { let tag: Int = menu.tag if (tag % 1000 > 0) { let market: Market = self.getMarket(tag % 100)! let isBtcRate: Bool = tag % 1000 > 100 let cost: String = self.getCost(coin.unit, market.name, isBtcRate, false) let title = NSMutableAttributedString(string: "") title.append(NSAttributedString(string: market.paddingName(), attributes: [NSFontAttributeName: NSFont.systemFont(ofSize: 14.0)])) title.append(NSAttributedString(string: cost, attributes: [NSFontAttributeName: NSFont.systemFont(ofSize: 14.0)])) menu.attributedTitle = title } } } } } } /** * Start notification timer * * @return nil */ func startNotification() { self.stopNotification() self.notificationTimer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(AppDelegate.notify), userInfo: nil, repeats: true) } /** * Stop notification timer * * @return nil */ func stopNotification() { self.notificationTimer.invalidate() } /** * notify * * @return nil */ func notify() { for index in 0..<self.getPreferencesNotifactions().count { NotificationSetting(self.getPreferencesNotifactions()[index]).notify(index) } } /** * Get currency rate * * @param String from * @param String to * @return Double rate */ func getCurrencyRate(_ from: String, _ to: String) -> Double { if (from == to || from == "BTC" || to == "BTC") { return 1 } else { return UserDefaults.standard.double(forKey: from + to) } } /** * Update currency rate * * @param String from * @param String to * @return nil */ func updateCurrencyRate(_ from: String, _ to: String) { if (from == to || from == "BTC" || to == "BTC" || UserDefaults.standard.double(forKey: from + to + "Time") > Date().timeIntervalSince1970 - 60 * 60) { return } let session = URLSession.shared let jsonUrl = URL(string: "https://api.manana.kr/exchange/rate/" + to + "/" + from + ".json") let task = session.dataTask(with: jsonUrl!, completionHandler: { (data, response, error) -> Void in do { let jsonData = try JSONSerialization.jsonObject(with: data!) as! [[String: Any]] if (jsonData.count == 1) { let time: Double = Date().timeIntervalSince1970 let rate: Double = jsonData[0]["rate"] as! Double UserDefaults.standard.set(rate, forKey: from + to) UserDefaults.standard.set(time, forKey: from + to + "Time") } } catch _ {} }) task.resume() } /** * Update ticker data * * @return nil */ func updateData() { for market in self.markets { if (self.isMarketEnabled(market.name) == true) { self.callMarketAPI(market) } } for (from, _) in self.currencies { for (to, _) in self.currencies { self.updateCurrencyRate(from, to) } } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY.MM.dd HH:mm:ss" let DateInFormat = dateFormatter.string(from: Date()) self.statusMenu.item(withTag: 100000)!.title = NSLocalizedString("menu.refresh", comment: "") + " : " + DateInFormat } /** * Call market's ticker API * * @param Market market * @return nil */ func callMarketAPI(_ market:Market) { var coins: [String: String] = [:] for coin in self.coins { if (self.isCoinEnabled(coin.unit) == true || (coin.unit == "BTC" && market.isBtcMarket == true)) { if (coin.marketParams[market.name] != nil) { coins[coin.unit] = coin.marketParams[market.name] } } } if (market.isCombination == true) { let session = URLSession.shared let apiUrl: URL = URL(string: market.api.url)! let task = session.dataTask(with: apiUrl, completionHandler: { (data, response, error) -> Void in do { if (data != nil) { let jsonData: [String: Any]? = try JSONSerialization.jsonObject(with: data!) as? [String: Any] if (jsonData != nil) { for (unit, param) in coins { let coin: Coin? = self.getCoin(unit) if (coin == nil) { continue } let coinData: [String: Any]? = jsonData![param] as? [String: Any] var last: Any? = coinData if (last == nil) { continue } for i in 0..<market.api.last.count { let key: String = market.api.last[i] if (Int(key) == nil) { let pointer: [String: Any]? = last as? [String: Any] last = pointer?[key] } else { let pointer: NSArray? = last as? NSArray last = pointer?[Int(key)!] } } if (last != nil) { let value: Double = self.getDouble(last!) self.costs[coin!.unit]![market.name] = value } if (market.api.isCompare == true) { if (market.api.change.count > 0) { var change: Any? = coinData for i in 0..<market.api.change.count { let key: String = market.api.change[i] if (Int(key) == nil) { let pointer: [String: Any]? = change as? [String: Any] change = pointer?[key] } else { let pointer: NSArray? = change as? NSArray change = pointer?[Int(key)!] } } if (change != nil) { let value: Double = self.getDouble(change!) * 100 self.costChanges[coin!.unit]![market.name] = value } } else { var first: Any? = coinData for i in 0..<market.api.first.count { let key: String = market.api.first[i] if (Int(key) == nil) { let pointer: [String: Any]? = first as? [String: Any] first = pointer?[key] } else { let pointer: NSArray? = first as? NSArray first = pointer?[Int(key)!] } } if (first != nil) { let value: Double = self.getDouble(first!) if (value > 0) { self.costChanges[coin!.unit]![market.name] = ((self.costs[coin!.unit]![market.name]! - value) / value) * 100 } } } } } } } } catch _ {} }) task.resume() } else { for (unit, param) in coins { let coin: Coin? = self.getCoin(unit) if (coin == nil) { continue } let session = URLSession.shared let apiUrl: URL = URL(string: market.api.url + param)! let task = session.dataTask(with: apiUrl, completionHandler: { (data, response, error) -> Void in do { if (data != nil) { let jsonData: [String: Any]? = try JSONSerialization.jsonObject(with: data!) as? [String: Any] if (jsonData != nil) { var last: Any? = jsonData for i in 0..<market.api.last.count { let key: String = market.api.last[i] if (key == "*") { let keyname: [String: Any]? = last as? [String: Any] if (keyname != nil) { for (_, object) in keyname! { last = object } } else { last = nil break } } else if (Int(key) == nil) { let pointer: [String: Any]? = last as? [String: Any] last = pointer?[key] } else { let pointer: NSArray? = last as? NSArray last = pointer?[Int(key)!] } } if (last != nil) { let value: Double = self.getDouble(last!) self.costs[coin!.unit]![market.name] = value } if (market.api.isCompare == true) { if (market.api.change.count > 0) { var change: Any? = jsonData for i in 0..<market.api.change.count { let key: String = market.api.change[i] if (key == "*") { let keyname: [String: Any]? = change as? [String: Any] if (keyname != nil) { for (_, object) in keyname! { change = object } } else { change = nil break } } else if (Int(key) == nil) { let pointer: [String: Any]? = change as? [String: Any] change = pointer?[key] } else { let pointer: NSArray? = change as? NSArray change = pointer?[Int(key)!] } } if (change != nil) { let value: Double = self.getDouble(change!) * 100 self.costChanges[coin!.unit]![market.name] = value } } else { var first: Any? = jsonData for i in 0..<market.api.first.count { let key: String = market.api.first[i] if (key == "*") { let keyname: [String: Any]? = first as? [String: Any] if (keyname != nil) { for (_, object) in keyname! { first = object } } else { first = nil break } } else if (Int(key) == nil) { let pointer: [String: Any]? = first as? [String: Any] first = pointer?[key] } else { let pointer: NSArray? = first as? NSArray first = pointer?[Int(key)!] } } if (first != nil) { let value: Double = self.getDouble(first!) if (value > 0) { self.costChanges[coin!.unit]![market.name] = ((self.costs[coin!.unit]![market.name]! - value) / value) * 100 } } } } } } } catch _ {} }) task.resume() } } } /** * Convert Any to Double * * @param Any number * @return Double number */ func getDouble(_ number: Any) -> Double { if (number is NSNumber) { return number as! Double } else if (number is NSString) { return Double(number as! String)! } else { return Double(0) } } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } /** * Get Refresh Interval * * @param NSPopUpButton sender * @return nil */ func getPreferencesRefreshInterval() -> Int { return self.getStorage("preferencesRefreshTime") == nil ? 300 : self.getStorage("preferencesRefreshTime") as! Int } /** * Get currency * * @return Int currency tag */ func getPreferencesCurrency() -> Int { return self.getStorage("preferencesCurrency") == nil ? 0 : self.getStorage("preferencesCurrency") as! Int } /** * Get Auto update interval * * @return Int update interval */ func getPreferencesAutoUpdate() -> Int { return self.getStorage("preferencesAutoUpdate") == nil ? 0 : self.getStorage("preferencesAutoUpdate") as! Int } /** * Get Auto enabled coin * * @return Bool isAutoEnabled */ func getPreferencesAutoEnabledCoin() -> Bool { return self.getStorage("preferencesAutoEnabledCoin") == nil ? false : self.getStorage("preferencesAutoEnabledCoin") as! Bool } /** * Get Auto enabled market * * @return Bool isAutoEnabled */ func getPreferencesAutoEnabledMarket() -> Bool { return self.getStorage("preferencesAutoEnabledMarket") == nil ? false : self.getStorage("preferencesAutoEnabledMarket") as! Bool } /** * Get start at login option * * @return Bool isStartAtLogin */ func getPreferencesStartAtLogin() -> Bool { let launcherAppIdentifier = "com.moimz.iCoinTickerLauncher" let startAtLogin = self.getStorage("preferencesStartAtLogin") as? Bool if (startAtLogin == nil) { SMLoginItemSetEnabled(launcherAppIdentifier as CFString, false) return false } else { SMLoginItemSetEnabled(launcherAppIdentifier as CFString, startAtLogin!) return startAtLogin! } } /** * Get ticker font size * * @return Int font size(pt) */ func getPreferencesFontSize() -> Int { return self.getStorage("preferencesFontSize") == nil ? 14 : self.getStorage("preferencesFontSize") as! Int } /** * Get ticker displayed currency * * @return Int displayedCurrency (0: none, 1: symbol, 2: code) */ func getPreferencesTickerDisplayedCurrency() -> Int { return self.getStorage("preferencesTickerDisplayedCurrency") == nil ? 0 : self.getStorage("preferencesTickerDisplayedCurrency") as! Int } /** * Get ticker displayed change * * @return Bool displayedChange */ func getPreferencesTickerDisplayedChange() -> Bool { return self.getStorage("preferencesTickerDisplayedChange") == nil ? false : self.getStorage("preferencesTickerDisplayedChange") as! Bool } /** * Get menu displayed currency * * @return Int displayedCurrency (1: symbol, 2: code) */ func getPreferencesMenuDisplayedCurrency() -> Int { return self.getStorage("preferencesTickerDisplayedCurrency") == nil ? 1 : self.getStorage("preferencesTickerDisplayedCurrency") as! Int } /** * Get menu displayed change * * @return Bool displayedChange */ func getPreferencesMenuDisplayedChange() -> Bool { return self.getStorage("preferencesMenuDisplayedChange") == nil ? false : self.getStorage("preferencesMenuDisplayedChange") as! Bool } /** * Get Notifications * * @return [NSDictionary] notifications */ func getPreferencesNotifactions() -> [NSDictionary] { return self.getStorage("notifications") == nil ? [] : self.getStorage("notifications") as! [NSDictionary] } /** * Check coins.plist update from github.com/moimz/iCoinTicker * * @param Any sender */ func checkUpdate(_ sender: Any) { if (sender is NSButton) { let button: NSButton = sender as! NSButton let loading: NSProgressIndicator = button.viewWithTag(-1) as! NSProgressIndicator button.title = "" button.isEnabled = false loading.startAnimation(nil) } else { if (self.getPreferencesAutoUpdate() == -1) { return } else if (self.getPreferencesAutoUpdate() > 0 && self.checkUpdateDate() < self.getPreferencesAutoUpdate()) { Timer.scheduledTimer(timeInterval: Double(self.getPreferencesAutoUpdate() * 60 * 60 * 24), target: self, selector: #selector(AppDelegate.checkUpdate), userInfo: nil, repeats: false) return } } let session = URLSession.shared let updateUrl: URL = URL(string: "https://raw.githubusercontent.com/moimz/iCoinTicker/master/coins.plist")! let task = session.dataTask(with: updateUrl, completionHandler: { (data, response, error) -> Void in do { if (data != nil) { let plist: NSMutableDictionary = try PropertyListSerialization.propertyList(from: data!, options: [], format: nil) as! NSMutableDictionary let updated: Date = plist["updated"] as! Date if (updated > self.plist["updated"] as! Date) { let fileName = "coins.plist" let documentsUrl: URL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!).appendingPathComponent(fileName) let content: String = String(data: data!, encoding: String.Encoding.utf8)! try content.write(to: documentsUrl, atomically: false, encoding: String.Encoding.utf8) self.checkUpdateAlert(updated, sender is NSButton ? sender : nil) } else if (sender is NSButton) { self.checkUpdateAlert(nil, sender) } UserDefaults.standard.set(Date().timeIntervalSince1970, forKey: "latestUpdatedTime") } else { self.checkUpdateAlert(nil, sender) } } catch _ { if (sender is NSButton) { self.checkUpdateAlert(nil, sender) } } }) task.resume() } /** * Check Lastest updated time * * @return Int date */ func checkUpdateDate() -> Int { let latestUpdatedTime: Double = UserDefaults.standard.double(forKey: "latestUpdatedTime") let now: Double = Date().timeIntervalSince1970 let date: Int = Int((now - latestUpdatedTime) / 60.0 / 60.0 / 24.0) return date } /** * Show alert message after checking updated coins.plist * * @param Date? updatedDate * @return nil */ func checkUpdateAlert(_ updatedDate: Date?, _ sender: Any?) { let isUpdated: Bool = updatedDate != nil var title: String = "" var message: String = "" if (isUpdated == true) { title = NSLocalizedString("preferences.coin.checkUpdate.true.title", comment:"") let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY.MM.dd HH:mm:ss" message = NSLocalizedString("preferences.coin.checkUpdate.true.date", comment:"") + ": " + dateFormatter.string(from: updatedDate!) message += "\n\n" + NSLocalizedString("preferences.coin.checkUpdate.true.message", comment:"") } else { title = NSLocalizedString("preferences.coin.checkUpdate.false.title", comment:"") message = NSLocalizedString("preferences.coin.checkUpdate.false.message", comment:"") } DispatchQueue.main.async { let alert: NSAlert = NSAlert() alert.alertStyle = NSAlertStyle.informational alert.messageText = title alert.informativeText = message if (isUpdated == true) { alert.addButton(withTitle: NSLocalizedString("button.relaunch", comment:"")) alert.addButton(withTitle: NSLocalizedString("button.cancel", comment:"")) } else { alert.addButton(withTitle: NSLocalizedString("button.close", comment:"")) alert.addButton(withTitle: NSLocalizedString("button.cancel", comment:"")) } if (self.preferencesWindow.isVisible == true) { alert.beginSheetModal(for: self.preferencesWindow, completionHandler: { (selected) -> Void in if (selected == NSAlertFirstButtonReturn) { if (isUpdated == true) { self.relaunch() } else if (sender != nil) { let button: NSButton = sender as! NSButton let loading: NSProgressIndicator = button.viewWithTag(-1) as! NSProgressIndicator loading.stopAnimation(nil) button.title = NSLocalizedString("preferences.coin.checkUpdate", comment: "") button.isEnabled = true } } else { if (isUpdated == true) { self.plist["updated"] = updatedDate let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY.MM.dd HH:mm:ss" let lastUpdate: NSTextField = self.preferencesCoin.viewWithTag(200) as! NSTextField lastUpdate.stringValue = NSLocalizedString("preferences.coin.lastUpdate", comment:"") + " : " + dateFormatter.string(from: self.plist["updated"] as! Date) } if (sender != nil) { let button: NSButton = sender as! NSButton let loading: NSProgressIndicator = button.viewWithTag(-1) as! NSProgressIndicator loading.stopAnimation(nil) button.title = NSLocalizedString("preferences.coin.checkUpdate", comment: "") button.isEnabled = true } } }) } else { let selected = alert.runModal() if (selected == NSAlertFirstButtonReturn) { if (isUpdated == true) { self.relaunch() } else if (sender != nil) { let button: NSButton = sender as! NSButton let loading: NSProgressIndicator = button.viewWithTag(-1) as! NSProgressIndicator loading.stopAnimation(nil) button.title = NSLocalizedString("preferences.coin.checkUpdate", comment: "") button.isEnabled = true } } else { if (isUpdated == true) { self.plist["updated"] = updatedDate let dateFormatter = DateFormatter() dateFormatter.dateFormat = "YYYY.MM.dd HH:mm:ss" let lastUpdate: NSTextField = self.preferencesCoin.viewWithTag(200) as! NSTextField lastUpdate.stringValue = NSLocalizedString("preferences.coin.lastUpdate", comment:"") + " : " + dateFormatter.string(from: self.plist["updated"] as! Date) } if (sender != nil) { let button: NSButton = sender as! NSButton let loading: NSProgressIndicator = button.viewWithTag(-1) as! NSProgressIndicator loading.stopAnimation(nil) button.title = NSLocalizedString("preferences.coin.checkUpdate", comment: "") button.isEnabled = true } } } } } /** * Force refresh * * @param NSMenuItem sender * @return nil */ func refresh(_ sender: NSMenuItem) { self.initCosts() self.stopTicker() self.updateTicker() self.updateData() self.startTicker() } /** * Open About window * * @param NSMenuItem sender * @return nil */ func openAboutWindow(_ sender: NSMenuItem) { self.aboutWindow.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) } /** * Open Prefrences window and Localizing window * * @param NSMenuItem sender * @return nil */ func openPreferencesWindow(_ sender: NSMenuItem) { self.preferencesWindow.makeKeyAndOrderFront(nil) self.preferencesWindow.title = NSLocalizedString("menu.preferences", comment: "") NSApp.activate(ignoringOtherApps: true) if (self.preferencesToolbar.selectedItemIdentifier == nil) { self.preferencesToolbar.selectedItemIdentifier = "general" preferencesViewSelected(self.preferencesToolbar.items[0]) } self.initPreferences() } /** * Preferences Toolbar Select * * @param NSToolbarItem sender * @ return nil */ func preferencesViewSelected(_ sender: NSToolbarItem) { var subview: NSView switch (sender.itemIdentifier) { case "general" : subview = self.preferencesGeneral case "appearance" : subview = self.preferencesAppearance case "coin" : subview = self.preferencesCoin case "notification" : subview = self.preferencesNotification case "donation" : subview = self.preferencesDonation default : subview = self.preferencesGeneral } let windowRect: NSRect = self.preferencesWindow.frame let viewRect: NSRect = subview.frame self.preferencesWindow.contentView!.isHidden = true self.preferencesWindow.contentView = subview let windowFrame: NSRect = NSMakeRect(windowRect.origin.x, windowRect.origin.y + (windowRect.size.height - viewRect.size.height - 78.0), viewRect.size.width, viewRect.size.height + 78.0) self.preferencesWindow.setFrame(windowFrame, display: true, animate: true) self.preferencesWindow.contentView!.isHidden = false } /** * Open sheet for notification edit * * @param Any sender * @return nil */ func openNotificationEditSheet(_ sender: Any) { let notificationEditView: NSView = self.notificationEditWindow.contentView! let coinButton: NSPopUpButton = notificationEditView.viewWithTag(10) as! NSPopUpButton let marketButton: NSPopUpButton = notificationEditView.viewWithTag(20) as! NSPopUpButton let currencyButton: NSPopUpButton = notificationEditView.viewWithTag(30) as! NSPopUpButton let priceInput: NSTextField = notificationEditView.viewWithTag(40) as! NSTextField let ruleButton: NSPopUpButton = notificationEditView.viewWithTag(50) as! NSPopUpButton let enabledButton: NSButton = notificationEditView.viewWithTag(60) as! NSButton let repeatedButton: NSButton = notificationEditView.viewWithTag(70) as! NSButton if (sender is NSTableView || sender is IndexSet) { var index: Int? = nil if (sender is NSTableView) { let tableView: NSTableView = sender as! NSTableView if (tableView.clickedRow == -1) { return } index = tableView.clickedRow } else { let indexes: NSIndexSet = sender as! NSIndexSet if (indexes.count != 1) { return } index = indexes.firstIndex } if (index == nil || index == -1) { return } let notification: NotificationSetting = NotificationSetting(self.getPreferencesNotifactions()[index!]) coinButton.selectItem(withTag: notification.coin.tag) self.setNotificationEditSheet(coinButton) marketButton.selectItem(withTag: notification.market.tag) self.setNotificationEditSheet(marketButton) currencyButton.selectItem(withTag: notification.currency.tag) self.setNotificationEditSheet(currencyButton) let numberFormatter: NumberFormatter = priceInput.formatter as! NumberFormatter priceInput.stringValue = numberFormatter.string(from: NSNumber(value: notification.price))! ruleButton.selectItem(withTag: notification.rule == ">=" ? 10 : 20) enabledButton.state = notification.enabled == true ? NSOnState : NSOffState repeatedButton.state = notification.repeated == true ? NSOnState : NSOffState notificationEditView.identifier = NSNumber(value: index!).stringValue } else { coinButton.selectItem(at: 0) self.setNotificationEditSheet(coinButton) marketButton.selectItem(at: 0) self.setNotificationEditSheet(marketButton) currencyButton.selectItem(withTag: self.getPreferencesCurrency()) self.setNotificationEditSheet(currencyButton) ruleButton.selectItem(at: 0) enabledButton.state = NSOnState repeatedButton.state = NSOffState notificationEditView.identifier = nil } self.preferencesWindow.beginSheet(self.notificationEditWindow, completionHandler: nil) self.notificationEditWindow.makeKeyAndOrderFront(nil) } /** * Set edit value in notification edit sheet * * @param NSPopUpButton sender * @return nil */ func setNotificationEditSheet(_ sender: NSPopUpButton) { let notificationEditView: NSView = self.notificationEditWindow.contentView! if (sender.tag == 10) { let coin: Coin = self.getCoin(sender.selectedItem!.tag)! let marketButton: NSPopUpButton = notificationEditView.viewWithTag(20) as! NSPopUpButton let selectedMarketTag: Int = marketButton.selectedItem!.tag marketButton.menu!.removeAllItems() for market in coin.markets { let menu: NSMenuItem = NSMenuItem() menu.title = market.name menu.tag = market.tag menu.image = NSImage(named: market.currency) marketButton.menu!.addItem(menu) } if (marketButton.menu!.item(withTag: selectedMarketTag) == nil) { marketButton.selectItem(at: 0) } else { marketButton.selectItem(withTag: selectedMarketTag) } self.setNotificationEditSheet(marketButton) } else if (sender.tag == 20) { let coin: Coin = self.getCoin((notificationEditView.viewWithTag(10) as! NSPopUpButton).selectedItem!.tag)! let market: Market = self.getMarket(sender.selectedItem!.tag)! let currencyButton: NSPopUpButton = notificationEditView.viewWithTag(30) as! NSPopUpButton let selectedCurrencyTag: Int = currencyButton.selectedItem!.tag currencyButton.menu!.removeAllItems() for (code, currency) in self.currencies { if (code == "BTC" && (coin.unit == "BTC" || market.isBtcMarket == false)) { continue } let menu: NSMenuItem = NSMenuItem() menu.title = currency.code + " (" + currency.mark + ")" menu.tag = currency.tag menu.identifier = code currencyButton.menu!.addItem(menu) } if (currencyButton.menu!.item(withTag: selectedCurrencyTag) == nil) { currencyButton.selectItem(at: 0) } else { currencyButton.selectItem(withTag: selectedCurrencyTag) } self.setNotificationEditSheet(currencyButton) } else if (sender.tag == 30) { let coinButton: NSPopUpButton = notificationEditView.viewWithTag(10) as! NSPopUpButton let coin: Coin = self.getCoin(coinButton.selectedItem!.tag)! let marketButton: NSPopUpButton = notificationEditView.viewWithTag(20) as! NSPopUpButton let market: Market = self.getMarket(marketButton.selectedItem!.tag)! let currency: Currency = self.getCurrency(sender.selectedItem!.identifier!)! let priceInput: NSTextField = notificationEditView.viewWithTag(40) as! NSTextField let numberFormatter = priceInput.formatter as! NumberFormatter numberFormatter.format = currency.format var cost: Double = 0 if (market.isBtcMarket == true && coin.unit != "BTC" && currency.code == "BTC") { cost = self.costs[coin.unit]![market.name]! priceInput.stringValue = numberFormatter.string(from: NSNumber(value: cost))! } else { if (market.isBtcMarket == true && coin.unit != "BTC") { cost = self.costs[coin.unit]![market.name]! * self.costs["BTC"]![market.name]! } else { cost = self.costs[coin.unit]![market.name]! } cost = cost * self.getCurrencyRate(market.currency, currency.code) priceInput.stringValue = numberFormatter.string(from: NSNumber(value: cost))! } } } /** * Save notifications * * @param Int lists index * @return nil */ func saveNotifications(_ index: Int) { self.stopNotification() let notificationEditView: NSView = self.notificationEditWindow.contentView! let coinButton: NSPopUpButton = notificationEditView.viewWithTag(10) as! NSPopUpButton let coin: Int = coinButton.selectedItem!.tag let marketButton: NSPopUpButton = notificationEditView.viewWithTag(20) as! NSPopUpButton let market: Int = marketButton.selectedItem!.tag let currencyButton: NSPopUpButton = notificationEditView.viewWithTag(30) as! NSPopUpButton let currency: String = currencyButton.selectedItem!.identifier! let priceInput: NSTextField = notificationEditView.viewWithTag(40) as! NSTextField let price: Double = Double(priceInput.stringValue.replacingOccurrences(of: ",", with: "")) == nil ? 0 : Double(priceInput.stringValue.replacingOccurrences(of: ",", with: ""))! let ruleButton: NSPopUpButton = notificationEditView.viewWithTag(50) as! NSPopUpButton let rule: String = ruleButton.selectedItem!.tag == 10 ? ">=" : "<=" let enabledButton: NSButton = notificationEditView.viewWithTag(60) as! NSButton let enabled: Bool = enabledButton.state == NSOnState let repeatedButton: NSButton = notificationEditView.viewWithTag(70) as! NSButton let repeated: Bool = repeatedButton.state == NSOnState let notification: NSMutableDictionary = NSMutableDictionary() notification.setValue(coin, forKey: "coin") notification.setValue(market, forKey: "market") notification.setValue(currency, forKey: "currency") notification.setValue(price, forKey: "price") notification.setValue(rule, forKey: "rule") notification.setValue(enabled, forKey: "enabled") notification.setValue(repeated, forKey: "repeated") var notifications: [NSDictionary] = self.getPreferencesNotifactions() if (index == -1) { notifications.append(notification) } else { notifications[index] = notification } self.setStorage("notifications", notifications) let tableView: NSTableView = self.preferencesNotification.viewWithTag(10) as! NSTableView tableView.reloadData() if (index > -1) { tableView.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false) } else if (notifications.count > 0) { tableView.selectRowIndexes(IndexSet(integer: notifications.count - 1), byExtendingSelection: false) } self.startNotification() } /** * Remove notifications * * @param Any sender * @return nil */ func removeNotifications(_ sender: Any) { self.stopNotification() let tableView: NSTableView = self.preferencesNotification.viewWithTag(10) as! NSTableView let indexes: NSIndexSet = tableView.selectedRowIndexes as NSIndexSet if (indexes.count == 0) { return } let alert: NSAlert = NSAlert() alert.alertStyle = NSAlertStyle.informational alert.messageText = NSLocalizedString("preferences.notification.remove", comment: "") alert.informativeText = NSLocalizedString("preferences.notification.removeHelp", comment: "").replacingOccurrences(of: "{COUNT}", with: NSNumber(value: indexes.count).stringValue) alert.addButton(withTitle: NSLocalizedString("button.delete", comment:"")) alert.addButton(withTitle: NSLocalizedString("button.cancel", comment:"")) alert.beginSheetModal(for: self.preferencesWindow, completionHandler: { (selected) -> Void in if (selected == NSAlertFirstButtonReturn) { var notifications: [NSDictionary] = [] for i in 0..<self.getPreferencesNotifactions().count { if (indexes.contains(i) == false) { notifications.append(self.getPreferencesNotifactions()[i]) } } self.setStorage("notifications", notifications) tableView.reloadData() } self.startNotification() }) } /** * Close or Save notification edit sheet * * @param NSButton sender * @return nil */ func closeNotificationEditSheet(_ sender: NSButton) { if (sender.tag == 100) { let notificationEditView: NSView = self.notificationEditWindow.contentView! let index: Int = notificationEditView.identifier == nil ? -1 : Int(notificationEditView.identifier!)! self.saveNotifications(index) } self.preferencesWindow.endSheet(self.notificationEditWindow) } /** * Set Refresh Interval * * @param NSPopUpButton sender * @return nil */ func setPreferencesRefreshInterval(_ sender: NSPopUpButton) { self.setStorage("preferencesRefreshTime", sender.selectedItem!.tag) self.timer.invalidate() self.timer = Timer.scheduledTimer(timeInterval: Double(sender.selectedItem!.tag), target: self, selector: #selector(AppDelegate.updateData), userInfo: nil, repeats: true) } /** * Set currency * * @param NSMenuItem sender * @return nil */ func setPreferencesCurrency(_ sender: NSMenuItem) { self.setStorage("preferencesCurrency", sender.tag) self.stopTicker() self.updateTicker() self.startTicker() } /** * Set Auto update * * @param Any sender * @return nil */ func setPreferencesAutoUpdate(_ sender: Any) { if (sender is NSPopUpButton) { let select: NSPopUpButton = sender as! NSPopUpButton self.setStorage("preferencesAutoUpdate", select.selectedItem!.tag) } else if (sender is NSButton) { let button: NSButton = sender as! NSButton if (button.state == NSOnState) { self.setStorage("preferencesAutoUpdate", 0) let select: NSPopUpButton = self.preferencesGeneral.viewWithTag(101) as! NSPopUpButton select.isEnabled = true select.select(select.menu!.item(withTag: 0)) } else { self.setStorage("preferencesAutoUpdate", -1) let select: NSPopUpButton = self.preferencesGeneral.viewWithTag(101) as! NSPopUpButton select.isEnabled = true select.select(select.menu!.item(withTag: 0)) select.isEnabled = false select.select(select.menu!.item(withTag: 0)) } } } /** * Set Auto Enabled Coin * * @param NSButton sender * @return nil */ func setPreferencesAutoEnabledCoin(_ sender: NSButton) { self.setStorage("preferencesAutoEnabledCoin", sender.state == NSOnState) } /** * Set Auto Enabled Market * * @param NSButton sender * @return nil */ func setPreferencesAutoEnabledMarket(_ sender: NSButton) { self.setStorage("preferencesAutoEnabledMarket", sender.state == NSOnState) } /** * Toggle start at login option * * @param NSButton sender * @return nil */ func setPreferencesStartAtLogin(_ sender: NSButton) { let launcherAppIdentifier = "com.moimz.iCoinTickerLauncher" SMLoginItemSetEnabled(launcherAppIdentifier as CFString, sender.state == NSOnState) self.setStorage("preferencesStartAtLogin", sender.state == NSOnState) self.killLauncher() } /** * Set ticker font size * * @param NSPopUpButton sender * @return nil */ func setPreferencesFontSize(_ sender: NSPopUpButton) { self.setStorage("preferencesFontSize", sender.selectedItem!.tag) self.stopTicker() self.updateTicker() self.startTicker() } /** * Set ticker displayed currency * * @param NSPopUpButton sender * @return nil */ func setPreferencesTickerDisplayedCurrency(_ sender: NSPopUpButton) { self.setStorage("preferencesTickerDisplayedCurrency", sender.selectedItem!.tag) self.stopTicker() self.updateTicker() self.startTicker() } /** * Set ticker displayed change * * @param NSButton sender * @return nil */ func setPreferencesTickerDisplayedChange(_ sender: NSButton) { self.setStorage("preferencesTickerDisplayedChange", sender.state == NSOnState) self.stopTicker() self.updateTicker() self.startTicker() } /** * Set menu displayed currency * * @param NSPopUpButton sender * @return nil */ func setPreferencesMenuDisplayedCurrency(_ sender: NSPopUpButton) { self.setStorage("preferencesMenuDisplayedCurrency", sender.selectedItem!.tag) self.stopTicker() self.updateTicker() self.startTicker() } /** * Set menu displayed change * * @param NSButton sender * @return nil */ func setPreferencesMenuDisplayedChange(_ sender: NSButton) { self.setStorage("preferencesMenuDisplayedChange", sender.state == NSOnState) self.stopTicker() self.updateTicker() self.startTicker() } /** * Set Enabled Coin * * @param NSButton sender * @return nil */ func setPreferencesCoinEnabled(_ sender: NSButton) { let coin: Coin = self.getCoin(sender.tag)! let enabledCoins: NSMutableDictionary = self.getStorage("preferencesEnabledCoins") as? NSDictionary == nil ? NSMutableDictionary() : (self.getStorage("preferencesEnabledCoins") as! NSDictionary).mutableCopy() as! NSMutableDictionary self.stopTicker() enabledCoins.setValue(sender.state == NSOnState, forKey: coin.unit) self.setStorage("preferencesEnabledCoins", enabledCoins) self.initMenus() self.updateTicker() self.startTicker() } /** * Set Enabled Market * * @param NSButton sender * @return nil */ func setPreferencesMarketEnabled(_ sender: NSButton) { let market: Market = self.getMarket(sender.tag)! let enabledMarkets: NSMutableDictionary = self.getStorage("preferencesEnabledMarkets") as? NSDictionary == nil ? NSMutableDictionary() : (self.getStorage("preferencesEnabledMarkets") as! NSDictionary).mutableCopy() as! NSMutableDictionary self.stopTicker() enabledMarkets.setValue(sender.state == NSOnState, forKey: market.name) self.setStorage("preferencesEnabledMarkets", enabledMarkets) self.initMenus() self.updateTicker() self.startTicker() } /** * Quit app * * @param AnyObject sender * @return nil */ func quit(_ sender: AnyObject) { self.timer.invalidate() self.tickerTimer.invalidate() NSApplication.shared().terminate(nil) } /** * Relaunch app after coin.plist update * * @return nil */ func relaunch() { let task = Process() var args = [String]() args.append("-c") let bundle = Bundle.main.bundlePath args.append("sleep 0.2; open \"\(bundle)\"") task.launchPath = "/bin/sh" task.arguments = args task.launch() NSApplication.shared().terminate(nil) } /** * Donate Button (IAP) * * @param NSButton sender * @return nil */ func donate(_ sender: NSButton) { if (sender.identifier == nil) { return } let loading: NSProgressIndicator = sender.viewWithTag(-1) as! NSProgressIndicator sender.title = "" sender.isEnabled = false loading.startAnimation(nil) let item: SKProduct? = self.donations[sender.identifier!] if (item != nil) { let payment = SKPayment(product: item!) SKPaymentQueue.default().add(payment) } } /** * Show alert message after purchase * * @param Bool success * @return nil */ func donateAlert(_ success: Bool) { var title: String = "" var message: String = "" if (success == true) { title = NSLocalizedString("preferences.donation.success.title", comment:"") message = NSLocalizedString("preferences.donation.success.message", comment:"") } else { title = NSLocalizedString("preferences.donation.fail.title", comment:"") message = NSLocalizedString("preferences.donation.fail.message", comment:"") } DispatchQueue.main.async { let alert: NSAlert = NSAlert() alert.alertStyle = NSAlertStyle.informational alert.messageText = title alert.icon = NSImage(named: "donation") alert.informativeText = message alert.addButton(withTitle: NSLocalizedString("button.close", comment:"")) if (self.preferencesWindow.isVisible == true) { alert.beginSheetModal(for: self.preferencesWindow, completionHandler: { (selected) -> Void in if (selected == NSAlertFirstButtonReturn) { for tag in 1...4 { let button: NSButton = self.preferencesDonation.viewWithTag(tag * 10) as! NSButton if (button.isEnabled == false) { let loading: NSProgressIndicator = button.viewWithTag(-1) as! NSProgressIndicator let product: SKProduct? = self.donations[button.identifier!] if (product == nil) { continue } var title: String = "" if (product!.priceLocale.currencyCode != nil) { title += product!.priceLocale.currencyCode! } else if (product!.priceLocale.currencySymbol != nil) { title += product!.priceLocale.currencySymbol! } button.title = title + " " + product!.price.stringValue button.isEnabled = true loading.stopAnimation(nil) } } } }) } else { let selected = alert.runModal() if (selected == NSAlertFirstButtonReturn) { for tag in 1...4 { let button: NSButton = self.preferencesDonation.viewWithTag(tag * 10) as! NSButton if (button.isEnabled == false) { let loading: NSProgressIndicator = button.viewWithTag(-1) as! NSProgressIndicator let product: SKProduct? = self.donations[button.identifier!] if (product == nil) { continue } var title: String = "" if (product!.priceLocale.currencyCode != nil) { title += product!.priceLocale.currencyCode! } else if (product!.priceLocale.currencySymbol != nil) { title += product!.priceLocale.currencySymbol! } button.title = title + " " + product!.price.stringValue button.isEnabled = true loading.stopAnimation(nil) } } } } } } /** * Cost changed notification * * @param Coin coin * @param String price * @return nil */ func showCostNotification(_ coin:Coin, _ price: String) { let notification = NSUserNotification() notification.title = NSLocalizedString("notification.cost.title", comment: "").replacingOccurrences(of: "{COIN}", with: coin.name) notification.subtitle = price notification.soundName = NSUserNotificationDefaultSoundName NSUserNotificationCenter.default.deliver(notification) } /** * Get value in storage for key */ func getStorage(_ key: String) -> Any? { return self.preferences.object(forKey: key) } /** * Set value in storage for key */ func setStorage(_ key:String, _ value: Any) { self.preferences.set(value, forKey: key) self.preferences.synchronize() } /** * KeyStore did changed */ func ubiquitousKeyValueStoreDidChange(notification: NSNotification) { let changedKeys = notification.userInfo?[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String] if (changedKeys != nil) { if (changedKeys!.contains("preferencesEnabledCoins") == true || changedKeys!.contains("preferencesEnabledMarkets") == true || changedKeys!.contains("preferencesMarketSelected") == true) { self.stopTicker() self.initMenus() self.startTicker() } } self.initPreferences() } @IBAction func openUrl(_ sender: AnyObject) { NSWorkspace.shared().open(URL(string: "https://github.com/moimz/iCoinTicker/issues")!) } } /** * NSTextField with Keyboard short */ class NSTableViewWithShortcut: NSTableView { private let commandKey = NSEventModifierFlags.command.rawValue private let commandShiftKey = NSEventModifierFlags.command.rawValue | NSEventModifierFlags.shift.rawValue override func performKeyEquivalent(with event: NSEvent) -> Bool { if (event.type == NSEventType.keyDown) { if ((event.modifierFlags.rawValue & NSEventModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey) { switch (event.keyCode) { case 0x00 : self.selectAll(nil) return true default : break } } else { switch (event.keyCode) { case 0x33 : let appDelegate = NSApplication.shared().delegate as! AppDelegate if (self.selectedRowIndexes.count > 0) { appDelegate.removeNotifications(self) return true } break case 0x24 : if (self.selectedRowIndexes.count == 1) { let appDelegate = NSApplication.shared().delegate as! AppDelegate appDelegate.openNotificationEditSheet(self.selectedRowIndexes) return true } break default : break } } } return super.performKeyEquivalent(with: event) } } /** * NSTextField with Keyboard short */ class NSTextFieldWithShortcut: NSTextField { private let commandKey = NSEventModifierFlags.command.rawValue private let commandShiftKey = NSEventModifierFlags.command.rawValue | NSEventModifierFlags.shift.rawValue override func performKeyEquivalent(with event: NSEvent) -> Bool { if (event.type == NSEventType.keyDown) { if ((event.modifierFlags.rawValue & NSEventModifierFlags.deviceIndependentFlagsMask.rawValue) == commandKey) { switch (event.keyCode) { case 0x07 : if NSApp.sendAction(#selector(NSText.cut(_:)), to:nil, from:self) { return true } case 0x08 : if NSApp.sendAction(#selector(NSText.copy(_:)), to:nil, from:self) { return true } case 0x09 : if NSApp.sendAction(#selector(NSText.paste(_:)), to:nil, from:self) { return true } case 0x00 : if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to:nil, from:self) { return true } default : break } } } return super.performKeyEquivalent(with: event) } } /** * IAP extension */ extension AppDelegate: SKPaymentTransactionObserver, SKProductsRequestDelegate { func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { for transaction in transactions as [SKPaymentTransaction] { switch (transaction.transactionState) { case SKPaymentTransactionState.purchased : SKPaymentQueue.default().finishTransaction(transaction) self.donateAlert(true) break case SKPaymentTransactionState.failed : SKPaymentQueue.default().finishTransaction(transaction) self.donateAlert(false) break default: break } } } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { for product in response.products { let tag: Int = Int(product.productIdentifier.replacingOccurrences(of: "com.moimz.iCoinTicker.donation.tier", with: ""))! * 10 let button: NSButton = self.preferencesDonation.viewWithTag(tag) as! NSButton var title: String = "" if (product.priceLocale.currencyCode != nil) { title += product.priceLocale.currencyCode! } else if (product.priceLocale.currencySymbol != nil) { title += product.priceLocale.currencySymbol! } button.title = title + " " + product.price.stringValue button.action = #selector(AppDelegate.donate) button.isEnabled = true button.identifier = product.productIdentifier self.donations[product.productIdentifier] = product } } } /** * Table view extension */ extension AppDelegate: NSTableViewDataSource, NSTableViewDelegate { func numberOfRows(in tableView: NSTableView) -> Int { if (tableView.identifier == "coins") { return self.coins.count } else if (tableView.identifier == "markets") { return self.markets.count } else if (tableView.identifier == "notifications") { return self.getPreferencesNotifactions().count } return 0 } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { if (tableView.identifier == "coins") { let coin: Coin = self.coins[row] if (tableColumn?.identifier == "unit") { let check: NSButton = tableView.make(withIdentifier:(tableColumn?.identifier)!, owner: self) as! NSButton check.tag = coin.tag check.action = #selector(AppDelegate.setPreferencesCoinEnabled) check.state = self.isCoinEnabled(coin.unit) == true ? NSOnState : NSOffState let title = NSMutableAttributedString(string: "") title.append(NSAttributedString(string: coin.mark, attributes: [NSFontAttributeName: NSFont(name: "cryptocoins-icons", size: 12.0)!])) title.append(NSAttributedString(string: " " + coin.unit, attributes: [NSFontAttributeName: NSFont.systemFont(ofSize: 13.0), NSBaselineOffsetAttributeName: -1.5])) check.attributedTitle = title return check } else if (tableColumn?.identifier == "name") { let cell: NSTableCellView = tableView.make(withIdentifier:(tableColumn?.identifier)!, owner: self) as! NSTableCellView cell.textField?.stringValue = coin.name return cell } } else if (tableView.identifier == "markets") { let market: Market = self.markets[row] if (tableColumn?.identifier == "market") { let check: NSButton = tableView.make(withIdentifier:(tableColumn?.identifier)!, owner: self) as! NSButton check.tag = market.tag check.title = market.name check.action = #selector(AppDelegate.setPreferencesMarketEnabled) check.state = self.isMarketEnabled(market.name) == true ? NSOnState : NSOffState return check } else if (tableColumn?.identifier == "currency") { let cell: NSTableCellView = tableView.make(withIdentifier:(tableColumn?.identifier)!, owner: self) as! NSTableCellView cell.imageView?.image = NSImage(named: market.currency) cell.textField?.stringValue = market.currency return cell } } else if (tableView.identifier == "notifications") { let cell: NSTableCellView = tableView.make(withIdentifier:(tableColumn?.identifier)!, owner: self) as! NSTableCellView let notification: NotificationSetting = NotificationSetting(self.getPreferencesNotifactions()[row]) if (tableColumn?.identifier == "coin") { let title = NSMutableAttributedString(string: "") title.append(NSAttributedString(string: notification.coin.mark, attributes: [NSFontAttributeName: NSFont(name: "cryptocoins-icons", size: 12.0)!])) title.append(NSAttributedString(string: " " + notification.coin.unit, attributes: [NSFontAttributeName: NSFont.systemFont(ofSize: 13.0), NSBaselineOffsetAttributeName: -1.5])) cell.textField?.attributedStringValue = title } if (tableColumn?.identifier == "market") { cell.textField?.stringValue = notification.market.name } if (tableColumn?.identifier == "rule") { let numberFormatter = NumberFormatter() numberFormatter.format = notification.currency.format cell.textField?.stringValue = notification.rule + " " + notification.currency.code + " " + numberFormatter.string(from: NSNumber(value: notification.price))! } if (tableColumn?.identifier == "status") { cell.textField?.stringValue = notification.enabled == true ? (notification.repeated == true ? NSLocalizedString("preferences.notification.status.repeated", comment: "") : NSLocalizedString("preferences.notification.status.enabled", comment: "")) : NSLocalizedString("preferences.notification.status.disabled", comment: "") } return cell } return nil } }
mit
be39719194a5092938f8217b0d5dfa66
40.914348
338
0.533373
5.688214
false
false
false
false
ZhipingYang/UUChatSwift
UUChatTableViewSwift/Source/View+SnapKit.swift
17
8244
// // SnapKit // // Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) import UIKit public typealias View = UIView #else import AppKit public typealias View = NSView #endif /** Used to expose public API on views */ public extension View { /// left edge public var snp_left: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Left) } /// top edge public var snp_top: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Top) } /// right edge public var snp_right: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Right) } /// bottom edge public var snp_bottom: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Bottom) } /// leading edge public var snp_leading: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Leading) } /// trailing edge public var snp_trailing: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Trailing) } /// width dimension public var snp_width: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Width) } /// height dimension public var snp_height: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Height) } /// centerX position public var snp_centerX: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterX) } /// centerY position public var snp_centerY: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterY) } /// baseline position public var snp_baseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Baseline) } #if os(iOS) /// first baseline position public var snp_firstBaseline: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.FirstBaseline) } /// left margin public var snp_leftMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeftMargin) } /// right margin public var snp_rightMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.RightMargin) } /// top margin public var snp_topMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TopMargin) } /// bottom margin public var snp_bottomMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.BottomMargin) } /// leading margin public var snp_leadingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.LeadingMargin) } /// trailing margin public var snp_trailingMargin: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.TrailingMargin) } /// centerX within margins public var snp_centerXWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterXWithinMargins) } /// centerY within margins public var snp_centerYWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterYWithinMargins) } #endif // top + left + bottom + right edges public var snp_edges: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Edges) } // width + height dimensions public var snp_size: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Size) } // centerX + centerY positions public var snp_center: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Center) } #if os(iOS) // top + left + bottom + right margins public var snp_margins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.Margins) } // centerX + centerY within margins public var snp_centerWithinMargins: ConstraintItem { return ConstraintItem(object: self, attributes: ConstraintAttributes.CenterWithinMargins) } #endif /** Prepares constraints with a `ConstraintMaker` and returns the made constraints but does not install them. :param: closure that will be passed the `ConstraintMaker` to make the constraints with :returns: the constraints made */ public func snp_prepareConstraints(file: String = __FILE__, line: UInt = __LINE__, @noescape closure: (make: ConstraintMaker) -> Void) -> [Constraint] { return ConstraintMaker.prepareConstraints(view: self, file: file, line: line, closure: closure) } /** Makes constraints with a `ConstraintMaker` and installs them along side any previous made constraints. :param: closure that will be passed the `ConstraintMaker` to make the constraints with */ public func snp_makeConstraints(file: String = __FILE__, line: UInt = __LINE__, @noescape closure: (make: ConstraintMaker) -> Void) -> Void { ConstraintMaker.makeConstraints(view: self, file: file, line: line, closure: closure) } /** Updates constraints with a `ConstraintMaker` that will replace existing constraints that match and install new ones. For constraints to match only the constant can be updated. :param: closure that will be passed the `ConstraintMaker` to update the constraints with */ public func snp_updateConstraints(file: String = __FILE__, line: UInt = __LINE__, @noescape closure: (make: ConstraintMaker) -> Void) -> Void { ConstraintMaker.updateConstraints(view: self, file: file, line: line, closure: closure) } /** Remakes constraints with a `ConstraintMaker` that will first remove all previously made constraints and make and install new ones. :param: closure that will be passed the `ConstraintMaker` to remake the constraints with */ public func snp_remakeConstraints(file: String = __FILE__, line: UInt = __LINE__, @noescape closure: (make: ConstraintMaker) -> Void) -> Void { ConstraintMaker.remakeConstraints(view: self, file: file, line: line, closure: closure) } /** Removes all previously made constraints. */ public func snp_removeConstraints() { ConstraintMaker.removeConstraints(view: self) } internal var snp_installedLayoutConstraints: [LayoutConstraint] { get { if let constraints = objc_getAssociatedObject(self, &installedLayoutConstraintsKey) as? [LayoutConstraint] { return constraints } return [] } set { objc_setAssociatedObject(self, &installedLayoutConstraintsKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } private var installedLayoutConstraintsKey = ""
mit
9a370cb2784d92779562ed552b081f49
44.8
156
0.713974
5.191436
false
false
false
false
brlittle86/picfeed
PicFeed/PicFeed/GalleryCollectionViewLayout.swift
1
947
// // GalleryCollectionViewLayout.swift // PicFeed // // Created by Brandon Little on 3/29/17. // Copyright © 2017 Brandon Little. All rights reserved. // import UIKit class GalleryCollectionViewLayout: UICollectionViewFlowLayout { var columns = 2 let spacing: CGFloat = 1.0 var screenWidth : CGFloat { return UIScreen.main.bounds.width } var itemWidth : CGFloat { let availableScreen = screenWidth - (CGFloat(self.columns) * self.spacing) return availableScreen / CGFloat(self.columns) } init(columns : Int = 2) { self.columns = columns super.init() self.minimumLineSpacing = spacing self.minimumInteritemSpacing = spacing self.itemSize = CGSize(width: itemWidth, height: itemWidth) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
307a9e6f40888c9ead2c6fe02aedb61b
23.25641
82
0.634249
4.660099
false
false
false
false
manavgabhawala/MGDocIt
MGDocIt/Documentable.swift
1
6681
// // Documentable.swift // MGDocIt // // Created by Manav Gabhawala on 16/08/15. // Copyright © 2015 Manav Gabhawala. All rights reserved. // import Foundation /// The types that are documentable. These are the only kinds of tokens that the `Documentable` protocol can parse and render properly. enum DocumentableType { case String case Bool case Array } /// A protocol which types conform to, to be able to be documented. protocol DocumentType { /// The documentation for a particular type. /// /// - Parameter indentation: This is a parameter of type `String`. The indentation to use while creating the documentation /// - Returns: The complete documentation string. func documentationWithIndentation(indentation: String) -> String } /// A protocol which if types conform to can handle parsing, replacing tokens and using custom user defined text. protocol Documentable: DocumentType { /// The key for the type which is used in conjunction with NSUserDefaults to set a custom string. var key: String { get } /// The default text to use if no user defined type is available. var defaultText: String { get } /// A dictionary of tokens that can be used in conjunction with this type. Each value of the dictionary is a tuple with a user displayable name and the type that the key returns. var availableTokens: [String: (String, DocumentableType)] { get } /// When an availableToken returns DocumentableType.String, this function will be invoked with that token to get the dynamic value represented for that token for the doc. /// /// - Parameter token: This is a parameter of type `String`. The token passed through available tokens. /// /// - Returns: A string represented by the token. Nil if the token doesn't represent a String func stringForToken(token: String) -> String? /// When an availableToken returns DocumentableType.Array, this function will be invoked with that token to get the dynamic value represented for that token for the doc. /// /// - Parameter token: This is a parameter of type `String`. The token passed through available tokens. /// /// - Returns: An array of strings represented by the token. Nil if the token doesn't represent an array func arrayForToken(token: String) -> [String]? /// When an availableToken returns DocumentableType.Bool, this function will be invoked with that token to get the dynamic value represented for that token for the doc. /// /// - Parameter token: This is a parameter of type `String`. The token passed through available tokens. /// /// - Returns: A boolean represented by the token. Nil if the token doesn't represent a Bool func boolForToken(token: String) -> Bool? } extension Documentable { func documentationWithIndentation(indentation: String) -> String { let begin : String let beginningDoc = MGDocItSetting.beginningDoc if beginningDoc.isEmpty { begin = "" } else { begin = indentation + beginningDoc + "\n" } let end : String let endingDoc = MGDocItSetting.endingDoc if endingDoc.isEmpty { end = "" } else { end = "\n" + indentation + endingDoc } var docText = MGDocItSetting.getCustomDocumentationForKey(key, defaultText: defaultText) for tokenIndex in 0..<availableTokens.count { let tokenStr = "#$\(tokenIndex)" let token = availableTokens[tokenStr]! switch token.1 { case .String: while let replaceRange = docText.rangeOfString(tokenStr), let replaceWith = stringForToken(tokenStr) { docText.replaceRange(replaceRange, with: replaceWith) } continue case .Bool: let startStr = "if\(tokenStr)" let elseStr = "else\(tokenStr)" let endStr = "end\(tokenStr)" while let boolValue = boolForToken(tokenStr), let startRange = docText.rangeOfString(startStr), let endRange = docText.rangeOfString(endStr) { if let half = docText.rangeOfString(elseStr) { if boolValue { docText.removeRange(half.startIndex, end: endRange.endIndex) docText.removeRange(startRange) } else { docText.removeRange(endRange) docText.removeRange(startRange.startIndex, end: half.endIndex) } } else { if boolValue { docText.removeRange(endRange) docText.removeRange(startRange) } else { docText.removeRange(startRange.startIndex, end: endRange.endIndex) } } } continue case .Array: while let arrayValue = arrayForToken(tokenStr), let tokenRange = docText.rangeOfString(tokenStr) { if let singleTokenRange = docText.rangeOfString("<\(tokenStr)>") { // Specially wrapped in < > then expand in place if arrayValue.count == 0 { docText.replaceRange(singleTokenRange, with: "<#Description#>") } else { let str = arrayValue.reduce("", combine: { "\($0)\($1), " }) let replaceTok = str.substringToIndex(str.endIndex.advancedBy(-2)) docText.replaceRange(singleTokenRange, with: "\(replaceTok)") } continue } let (line, lineRange) = docText.lineContainingRange(tokenRange) if tokenStr == "#$1" && line.rangeOfString("#$2") != nil, let typeArrayValue = arrayForToken("#$2") { let lineTemplate = line.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet()) // Special function case assert(arrayValue.count == typeArrayValue.count) var textToReplaceWith = "" if arrayValue.count > 0 && !docText.isEmpty { textToReplaceWith += "\n" } for (i, elem) in arrayValue.enumerate() { textToReplaceWith += "\n" textToReplaceWith += lineTemplate.stringByReplacingOccurrencesOfString(tokenStr, withString: elem).stringByReplacingOccurrencesOfString("#$2", withString: typeArrayValue[i]) } if !textToReplaceWith.isEmpty { textToReplaceWith += "\n" } docText.replaceRange(lineRange, with: textToReplaceWith) } else { let initial = docText.isEmpty ? "" : "\n" let newString = arrayValue.reduce(initial, combine: { "\($0)\(line.stringByReplacingOccurrencesOfString(tokenStr, withString: $1))\n" }) docText.replaceRange(lineRange, with: newString) } } continue } } docText = docText.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) let prefix : String if docText.rangeOfString("// ") == nil { prefix = indentation + MGDocItSetting.linePrefix } else { prefix = indentation } return begin + prefix + docText.stringByReplacingOccurrencesOfString("\n", withString: "\n\(prefix)") + end } }
mit
97b3107d9992eca18993eef8ec8e7567
32.737374
180
0.689072
4.143921
false
false
false
false
baiyidjp/SwiftWB
SwiftWeibo/SwiftWeibo/Classes/Tools(工具)/SwiftExtension/UIImageView+WebImage.swift
1
1118
// // UIImageView+WebImage.swift // SwiftWeibo // // Created by tztddong on 2016/11/30. // Copyright © 2016年 dongjiangpeng. All rights reserved. // import Foundation extension UIImageView { /// 封装SDWebImage /// /// - Parameters: /// - urlString: 图像URL /// - placeholderImage: 占位图 /// - isRound: 是否是圆形 func jp_setWebImage(urlString: String?,placeholderImage: UIImage?,isRound: Bool = false,backColor: UIColor = UIColor.white,lineColor: UIColor = UIColor.lightGray) { guard let urlString = urlString, let url = URL(string: urlString) else { //设置占位图 然后返回 image = placeholderImage return } /// [weak self] 解决循环引用 sd_setImage(with: url, placeholderImage: placeholderImage, options: [], progress: nil) { [weak self](image, _, _, _) in if isRound { self?.image = image?.jp_newRoundImage(size: self?.bounds.size,backColor: backColor) } } } }
mit
6fedeebaacfd105c243371abd2f7b7e3
27.675676
168
0.564562
4.278226
false
false
false
false
KyoheiG3/RxSwift
RxExample/RxExample/Examples/WikipediaImageSearch/WikipediaAPI/WikipediaAPI.swift
8
2592
// // WikipediaAPI.swift // RxExample // // Created by Krunoslav Zaher on 3/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift import RxCocoa #endif func apiError(_ error: String) -> NSError { return NSError(domain: "WikipediaAPI", code: -1, userInfo: [NSLocalizedDescriptionKey: error]) } public let WikipediaParseError = apiError("Error during parsing") protocol WikipediaAPI { func getSearchResults(_ query: String) -> Observable<[WikipediaSearchResult]> func articleContent(_ searchResult: WikipediaSearchResult) -> Observable<WikipediaPage> } class DefaultWikipediaAPI: WikipediaAPI { static let sharedAPI = DefaultWikipediaAPI() // Singleton let $: Dependencies = Dependencies.sharedDependencies let loadingWikipediaData = ActivityIndicator() private init() {} private func JSON(_ url: URL) -> Observable<Any> { return $.URLSession .rx.json(url: url) .trackActivity(loadingWikipediaData) } // Example wikipedia response http://en.wikipedia.org/w/api.php?action=opensearch&search=Rx func getSearchResults(_ query: String) -> Observable<[WikipediaSearchResult]> { let escapedQuery = query.URLEscaped let urlContent = "http://en.wikipedia.org/w/api.php?action=opensearch&search=\(escapedQuery)" let url = URL(string: urlContent)! return JSON(url) .observeOn($.backgroundWorkScheduler) .map { json in guard let json = json as? [AnyObject] else { throw exampleError("Parsing error") } return try WikipediaSearchResult.parseJSON(json) } .observeOn($.mainScheduler) } // http://en.wikipedia.org/w/api.php?action=parse&page=rx&format=json func articleContent(_ searchResult: WikipediaSearchResult) -> Observable<WikipediaPage> { let escapedPage = searchResult.title.URLEscaped guard let url = URL(string: "http://en.wikipedia.org/w/api.php?action=parse&page=\(escapedPage)&format=json") else { return Observable.error(apiError("Can't create url")) } return JSON(url) .map { jsonResult in guard let json = jsonResult as? NSDictionary else { throw exampleError("Parsing error") } return try WikipediaPage.parseJSON(json) } .observeOn($.mainScheduler) } }
mit
e93b0fea29954e5d334c075333fa069f
32.649351
124
0.63103
4.815985
false
false
false
false
1457792186/JWSwift
SwiftLearn/SwiftDemo/SwiftDemo/UserCenter/JWUserIntegralViewController.swift
1
12109
// // JWUserIntegralViewController.swift // SwiftDemo // // Created by apple on 2017/11/8. // Copyright © 2017年 UgoMedia. All rights reserved. // import UIKit import MJRefresh class JWUserIntegralViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var integralTableView: UITableView! @IBOutlet weak var detailTableView: UITableView! var integralData:NSMutableArray = NSMutableArray() var detailPage:Int = 0 var detailData:NSMutableArray = NSMutableArray() var isDetail:Bool = false let integralTableHeader = "JWUserIntegralTableHeader" let integralTableFooter = "JWUserIntegralTableFooter" let integralTableCell = "JWUserIntegralTableViewCell" let detailTableHeader = "JWUserIntegralDetailTableHeader" let detailTableCell = "JWUserIntegralDetailTableViewCell" let integralBtn = UIButton.init(frame: CGRect.init(x: mainScreenWidth/2.0 - 71.0, y: 7.0, width: 70.0, height: 30.0)) let detailBtn = UIButton.init(frame: CGRect.init(x: mainScreenWidth/2.0 + 1.0, y: 7.0, width: 70.0, height: 30.0)) let chooseSliderView = UIImageView.init(frame: CGRect.init(x: 0, y: 42.5, width: 25.0, height: 5.0)) // MARK: - Function override func viewDidLoad() { super.viewDidLoad() self.prepareTable() self.prepareUI() self.setRefreshFunction() self.requestIntegralData() self.requestIntegralDetailData(isHeader: true) } override func viewWillAppear(_ animated: Bool) { integralBtn.isHidden = false detailBtn.isHidden = false chooseSliderView.isHidden = false } override func viewWillDisappear(_ animated: Bool) { integralBtn.isHidden = true detailBtn.isHidden = true chooseSliderView.isHidden = true } func prepareUI() { integralBtn.setTitle("积分", for: UIControlState.normal) integralBtn.setTitleColor(navTitleColor, for: UIControlState.normal) integralBtn.setTitleColor(colorMain, for: UIControlState.selected) integralBtn.titleLabel?.font = JWFontAdaptor.adjustFont(fixFont: UIFont.systemFont(ofSize: 15.0)) integralBtn.addTarget(self, action: #selector(JWUserIntegralViewController.viewTypeChangeBtnAction(sender:)), for: UIControlEvents.touchUpInside) self.navigationController?.navigationBar .addSubview(integralBtn) detailBtn.setTitle("详情", for: UIControlState.normal) detailBtn.setTitleColor(navTitleColor, for: UIControlState.normal) detailBtn.setTitleColor(colorMain, for: UIControlState.selected) detailBtn.titleLabel?.font = JWFontAdaptor.adjustFont(fixFont: UIFont.systemFont(ofSize: 15.0)) detailBtn.addTarget(self, action: #selector(JWUserIntegralViewController.viewTypeChangeBtnAction(sender:)), for: UIControlEvents.touchUpInside) self.navigationController?.navigationBar.addSubview(detailBtn) let lineView = UIView.init(frame: CGRect.init(x: detailBtn.frame.origin.x - 1.0, y: detailBtn.frame.origin.y, width: 0.5, height: (detailBtn.titleLabel?.font.pointSize)!)) lineView.backgroundColor = JWTools.colorWithHexString(hex: "#f6f6f6") self.navigationController?.navigationBar.addSubview(lineView) chooseSliderView.image = UIImage.init(named: "chooseSlider") chooseSliderView.center = CGPoint.init(x: integralBtn.center.x, y: chooseSliderView.center.y) self.navigationController?.navigationBar.addSubview(chooseSliderView) self.viewTypeChangeBtnAction(sender: integralBtn) } func prepareTable() { self.integralTableView.register(UINib(nibName: integralTableCell, bundle: nil), forCellReuseIdentifier: integralTableCell) self.integralTableView.register(UINib.init(nibName: integralTableHeader, bundle: nil), forHeaderFooterViewReuseIdentifier: integralTableHeader) self.integralTableView.register(UINib.init(nibName: integralTableFooter, bundle: nil), forHeaderFooterViewReuseIdentifier: integralTableFooter) self.detailTableView.register(UINib(nibName: detailTableCell, bundle: nil), forCellReuseIdentifier: detailTableCell) self.detailTableView.register(UINib.init(nibName: detailTableHeader, bundle: nil), forHeaderFooterViewReuseIdentifier: detailTableHeader) } // 点击类型切换按钮 @objc func viewTypeChangeBtnAction(sender: UIButton) { integralBtn.isSelected = sender.isEqual(integralBtn) detailBtn.isSelected = sender.isEqual(detailBtn) UIView.animate(withDuration: 0.2) { self.chooseSliderView.center = CGPoint.init(x: (self.integralBtn.isSelected ? self.integralBtn.center.x : self.detailBtn.center.x), y: self.chooseSliderView.center.y) } integralTableView.isHidden = !integralBtn.isSelected detailTableView.isHidden = !detailBtn.isSelected } // MARK: - UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ if tableView.isEqual(self.integralTableView) { return (integralData[section] as! NSArray).count + 1 }else{ return detailData.count } } func numberOfSections(in tableView: UITableView) -> Int{ return tableView.isEqual(self.integralTableView) ? 2 : 1; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView.isEqual(self.integralTableView) { let integralCell = tableView.dequeueReusableCell(withIdentifier: integralTableCell, for: indexPath) as! JWUserIntegralTableViewCell if indexPath.row == 0{ integralCell.setTopStyle() }else{ let model = (integralData[indexPath.section] as! NSArray)[indexPath.row - 1] integralCell.setData(dataModel: model as! JWUserIntegralModel) } return integralCell } let detailCell = tableView.dequeueReusableCell(withIdentifier: detailTableCell, for: indexPath) as! JWUserIntegralDetailTableViewCell let model = self.detailData[indexPath.row] as! JWUserIntegralDetailModel detailCell .setData(dataModel: model) return detailCell } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{ return tableView.isEqual(self.integralTableView) ? (indexPath.row == 0 ? 40.0 : 44.0) : 44.0 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{ return tableView.isEqual(self.integralTableView) ? 50.0 : 44.0 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{ return tableView.isEqual(self.integralTableView) ? (section == 0 ? 12.0 : 152.0) : 0.0001 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{ if tableView.isEqual(self.integralTableView) { let integralHeaderView = tableView.dequeueReusableHeaderFooterView(withIdentifier: integralTableHeader) as! JWUserIntegralTableHeader integralHeaderView.nameLabel.text = section == 0 ? "每日奖励积分规则" : "一次性奖励积分规则" return integralHeaderView }else{ let detailHeader = tableView.dequeueReusableHeaderFooterView(withIdentifier: detailTableHeader) as! JWUserIntegralDetailTableHeader return detailHeader } } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{ if tableView.isEqual(self.integralTableView) { if section == 0 { let footerView = UIView.init(frame: CGRect.init(x: 0.0, y: 0.0, width: mainScreenWidth, height: 12.0)) footerView.backgroundColor = JWTools.colorWithHexString(hex: "#f5f5f5") return footerView }else{ let integralFooterView = tableView.dequeueReusableHeaderFooterView(withIdentifier: integralTableFooter) return integralFooterView } }else{ return nil } } // MARK: - MJRefresh func setRefreshFunction() { self.integralTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { self.requestIntegralData() }) self.detailTableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { self.requestIntegralDetailData(isHeader:true) }) self.detailTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: { self.requestIntegralDetailData(isHeader:false) }) } // MARK: - RequestData // 请求积分数据 func requestIntegralData() { let dataArr = [ [ ["typeName":"今日签到","addIntegral":"10","introduce":"累计加分"], ["typeName":"发表帖子","addIntegral":"10","introduce":""], ["typeName":"回复","addIntegral":"2","introduce":""] ], [ ["typeName":"孕期账号注册","addIntegral":"100","introduce":"累计加分"], ["typeName":"完善个人资料","addIntegral":"50","introduce":""], ] ] for index in 0..<dataArr.count { let dataSubArr = dataArr[index] let data = NSMutableArray() for subIndex in 0..<dataSubArr.count { let dataDic = dataSubArr[subIndex] let model = JWUserIntegralModel.initModel(dataDic: dataDic as NSDictionary) data.add(model) } integralData.add(data) } //重现加载表格数据 self.integralTableView!.reloadData() //结束刷新 self.integralTableView!.mj_header.endRefreshing() } // 请求详情数据 func requestIntegralDetailData(isHeader:Bool) { let dataArr = [ ["typeName":"今日签到","addIntegral":"10","time":"1510296376"], ["typeName":"发表帖子","addIntegral":"10","time":"1508150376"], ["typeName":"回复","addIntegral":"2","time":"1508200376"], ["typeName":"今日签到","addIntegral":"10","time":"1508220376"], ["typeName":"发表帖子","addIntegral":"10","time":"1508400376"], ["typeName":"回复","addIntegral":"2","time":"1508600376"], ["typeName":"今日签到","addIntegral":"10","time":"1508606376"], ["typeName":"发表帖子","addIntegral":"10","time":"1509006376"], ["typeName":"回复","addIntegral":"2","time":"1509096376"], ["typeName":"今日签到","addIntegral":"10","time":"1509296376"], ["typeName":"发表帖子","addIntegral":"10","time":"1510096376"], ["typeName":"回复","addIntegral":"2","time":"1500296376"] ] // 下拉刷新重置 if isHeader { self.detailPage = 0 detailData.removeAllObjects() } for index in 0..<dataArr.count { let dataDic = dataArr[index] let model = JWUserIntegralDetailModel.initModel(dataDic: dataDic as NSDictionary) detailData.add(model) } self.detailPage += 1 //重现加载表格数据 self.detailTableView!.reloadData() //结束刷新 if isHeader { self.detailTableView!.mj_header.endRefreshing() }else{ self.detailTableView!.mj_footer.endRefreshing() } } }
apache-2.0
155df057d1147f56f150448076d6e8e6
40.780919
179
0.635572
5.035775
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/jump-game-vi.swift
2
883
/** * https://leetcode.com/problems/jump-game-vi/ * * */ // Date: Wed Jun 9 17:44:36 PDT 2021 class Solution { func maxResult(_ nums: [Int], _ k: Int) -> Int { var maxScore = Array(repeating: 0, count: nums.count) var slideWindow = [Int]() for index in 0 ..< nums.count { let maxValue = slideWindow.count > 0 ? maxScore[slideWindow.last ?? 0] : 0 let score = maxValue + nums[index] while let firstIndex = slideWindow.first, maxScore[firstIndex] < score { slideWindow.removeFirst() } slideWindow.insert(index, at: 0) while let last = slideWindow.last, last + k <= index { slideWindow.removeLast() } maxScore[index] = score // print(slideWindow, maxScore) } return maxScore.last ?? 0 } }
mit
b8223405419762dab2c8b85c0214151f
31.703704
86
0.539071
4.184834
false
false
false
false
railsware/Sleipnir
Sleipnir/Spec/Matchers/ExpectFailureWithMessage.swift
1
1470
// // ExpectFailureWithMessage.swift // Sleipnir // // Created by Artur Termenji on 7/11/14. // Copyright (c) 2014 railsware. All rights reserved. // import Foundation func expectFailureWithMessage(message: String, file: String = #file, line: Int = #line, block: SleipnirBlock) { let currentExample = Runner.currentExample let fakeExample = Example("I am fake", {}) Runner.currentExample = fakeExample func updateCurrentExample(state: ExampleState, specFailure: SpecFailure? = nil) { if specFailure != nil { currentExample!.specFailure = specFailure } currentExample!.setState(state) Runner.currentExample = currentExample } block() if fakeExample.failed() { if !(message == fakeExample.message()) { let reason = "Expected failure message: \(message) but received failure message \(fakeExample.message())" let specFailure = SpecFailure(reasonRaw: reason, fileName: file, lineNumber: line) updateCurrentExample(ExampleState.Failed, specFailure: specFailure) } else { updateCurrentExample(ExampleState.Passed) } } else { let reason = "Expectation should have failed" let specFailure = SpecFailure(reasonRaw: reason, fileName: file, lineNumber: line) updateCurrentExample(ExampleState.Failed, specFailure: specFailure) } }
mit
ead91e17e66590570403e810f88c75da
34.878049
108
0.644218
4.803922
false
false
false
false
janmchan/XCodeWar
War/War/ViewController.swift
1
1792
// // ViewController.swift // War // // Created by Jan Michael Chan on 14/01/16. // Copyright © 2016 Channies. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var firstCardImageView: UIImageView! @IBOutlet weak var secondCardImageView: UIImageView! @IBOutlet weak var playAroundButton: UIButton! @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var enemyScoreLabel: UILabel! @IBOutlet weak var playerScoreLabel: UILabel! var playerScore:Int = 0 var enemyScore:Int = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func playRoundTapped(sender: UIButton) { //self.playAroundButton.setTitle("Play Round", forState: UIControlState.Normal) let firstCard = arc4random_uniform(13) + 1 let secondCard = arc4random_uniform(13) + 1 let firstCardName = String(format: "card%i", firstCard) let secondCardName = String(format: "card%i", secondCard) self.firstCardImageView.image = UIImage(named: firstCardName) self.secondCardImageView.image = UIImage(named: secondCardName) if(firstCard > secondCard) { playerScore += 1 playerScoreLabel.text = String(playerScore) } else if(firstCard == secondCard) { //TODO: card are equal } else { enemyScore++ enemyScoreLabel.text = String(enemyScore) } } }
gpl-3.0
c470dd5cc71e307cfbb478528ca7bfe0
27.887097
87
0.636516
4.725594
false
false
false
false
NathanHaley/mobile_pick_largest_shape_game
GameMaxAreaPicker/ShapeButtons.swift
1
2081
import UIKit import CoreData // MARK: Parent shape class class CustomButton: UIButton { var fillColor: UIColor = UIColor.grayColor() var outlineColor: UIColor = UIColor.blackColor() var halfLineWidth: CGFloat = 3.0 //Controls border width var originalSize: CGSize = CGSize(width: 0.0, height: 0.0) var areaFactor: CGFloat! var area: CGFloat { return 0.0} override init(frame: CGRect) { super.init(frame: frame) self.opaque = false } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func drawRect(rect: CGRect) { outlineColor.setStroke() let outlinePath = getOutlinePath() outlinePath.lineWidth = 2.0 * halfLineWidth outlinePath.stroke() fillColor.setFill() outlinePath.fill() } //Blank placeholder, implemented in subclasses func getOutlinePath() -> UIBezierPath { return UIBezierPath() } } // MARK: Child shapes class CircleButton: CustomButton { override var area: CGFloat { return (bounds.width * 0.5) * (bounds.width * 0.5) * CGFloat(M_PI) } override func getOutlinePath() -> UIBezierPath { let outlinePath = UIBezierPath(ovalInRect: CGRect( x: halfLineWidth, y: halfLineWidth, width: bounds.size.width - 2 * halfLineWidth, height: bounds.size.height - 2 * halfLineWidth)) return outlinePath } } class SquareButton: CustomButton { override var area: CGFloat { return bounds.width * bounds.width } override func getOutlinePath() -> UIBezierPath { let outlinePath = UIBezierPath(rect: CGRect( x: halfLineWidth, y: halfLineWidth, width: bounds.size.width - 2 * halfLineWidth, height: bounds.size.height - 2 * halfLineWidth)) return outlinePath } }
mit
a90682483057e201b092d4c9a65adf28
22.382022
101
0.578087
5.038741
false
false
false
false
LongPF/FaceTube
FaceTube/Tool/Capture/FTFiltersPickerView.swift
1
2794
// // FTFiltersPickerView.swift // FaceTube // // Created by 龙鹏飞 on 2017/6/8. // Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved. // import UIKit import SnapKit class FTFiltersPickerView: UIView { var picker: UIPickerView! override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func initialize(){ picker = UIPickerView() picker.dataSource = self picker.delegate = self picker.showsSelectionIndicator = false self.addSubview(picker) picker.transform = CGAffineTransform.init(rotationAngle: -.pi/2.0) picker.snp.makeConstraints { (make) in make.centerX.equalTo(self.snp.centerX) make.centerY.equalTo(self.snp.centerY) make.height.equalTo(self.snp.width) make.width.equalTo(self.snp.height) } } } extension FTFiltersPickerView: UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { //隐藏分割线 分割线的高度为0.5 pickerView.subviews.forEach { $0.isHidden = $0.frame.height < 1.0 } return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return FTPhotoFilters.filterDisplayNames().count } func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { let title: NSString = NSString.init(string: FTPhotoFilters.filterDisplayNames()[0]) return title.size(attributes: [NSFontAttributeName:UIFont.ft_regular(17)]).width+10 } } extension FTFiltersPickerView: UIPickerViewDelegate { func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let filterName = FTPhotoFilters.filterDisplayNames()[row]; let filter = FTPhotoFilters.filterForDisplayName(displayName: filterName) FTPhotoFilters.shared.selectedFilter = filter } func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var label: UILabel if let lb = view as? UILabel { label = lb }else{ label = UILabel() label.font = UIFont.ft_medium(17) label.textAlignment = .center label.textColor = UIColor.white } label.text = FTPhotoFilters.filterDisplayNames()[row] label.transform = CGAffineTransform.init(rotationAngle: .pi/2.0) return label } }
mit
7873358221b0aebdbde0c69e7c478b03
29.01087
132
0.634191
4.72774
false
false
false
false
tsaievan/XYReadBook
XYReadBook/XYReadBook/Classes/Views/Profile/XYProfileHeader.swift
1
2918
// // XYProfileHeader.swift // XYReadBook // // Created by tsaievan on 2017/9/1. // Copyright © 2017年 tsaievan. All rights reserved. // import UIKit import SnapKit class XYProfileHeader: UIView { /// 用户名Label lazy var userNameLabel = UILabel() /// 用户头像 lazy var iconBtn = UIButton(type: .custom) /// 点击切换提示Label lazy var tipLabel = UILabel() /// 签到Button lazy var signinBtn = UIButton(type: .custom) override init(frame: CGRect) { super.init(frame: frame) setupUI() makeConstrains() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 设置UI extension XYProfileHeader { fileprivate func setupUI() { ///< 设置用户名Label userNameLabel.text = "欣阅读书" userNameLabel.textColor = UIColor.darkGray userNameLabel.textAlignment = .center userNameLabel.sizeToFit() addSubview(userNameLabel) ///< 设置头像 iconBtn.setBackgroundImage((#imageLiteral(resourceName: "iTunesArtwork")), for: .normal) iconBtn.layer.masksToBounds = true iconBtn.layer.cornerRadius = 50 addSubview(iconBtn) ///< 设置点击切换提示Label tipLabel.text = "点击切换" tipLabel.textColor = UIColor.darkGray tipLabel.font = UIFont.systemFont(ofSize: 14) tipLabel.textAlignment = .center tipLabel.sizeToFit() addSubview(tipLabel) ///< 设置签到Button signinBtn.setBackgroundImage((#imageLiteral(resourceName: "signin")), for: .normal) signinBtn.setTitle("签到", for: .normal) signinBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13) signinBtn.setTitleColor(UIColor.hm_color(withHex: 0xFAA200), for: .normal) addSubview(signinBtn) } } // MARK: - 更新约束 extension XYProfileHeader { fileprivate func makeConstrains() { ///< 用户名Label约束 userNameLabel.snp.makeConstraints { (make) in make.top.equalTo(self).offset(16) make.centerX.equalTo(self) } ///< 头像约束 iconBtn.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(userNameLabel.snp.bottom).offset(10) make.width.equalTo(100) make.height.equalTo(100) } ///< 点击切换提示Label约束 tipLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self) make.top.equalTo(iconBtn.snp.bottom).offset(10) } ///< 签到Button约束 signinBtn.snp.makeConstraints { (make) in make.top.equalTo(userNameLabel) make.right.equalTo(self).offset(-16) } } }
mit
7071a689c64114177e96efe54ac8736b
26.69
96
0.599133
4.36063
false
false
false
false
apple/swift-nio
Sources/NIOPerformanceTester/NIOAsyncWriterSingleWritesBenchmark.swift
1
1852
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore import DequeModule import Atomics fileprivate struct NoOpDelegate: NIOAsyncWriterSinkDelegate, @unchecked Sendable { typealias Element = Int let counter = ManagedAtomic(0) func didYield(contentsOf sequence: Deque<Int>) { counter.wrappingIncrement(by: sequence.count, ordering: .relaxed) } func didTerminate(error: Error?) {} } // This is unchecked Sendable because the Sink is not Sendable but the Sink is thread safe @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) final class NIOAsyncWriterSingleWritesBenchmark: AsyncBenchmark, @unchecked Sendable { private let iterations: Int private let delegate: NoOpDelegate private let writer: NIOAsyncWriter<Int, NoOpDelegate> private let sink: NIOAsyncWriter<Int, NoOpDelegate>.Sink init(iterations: Int) { self.iterations = iterations self.delegate = .init() let newWriter = NIOAsyncWriter<Int, NoOpDelegate>.makeWriter(isWritable: true, delegate: self.delegate) self.writer = newWriter.writer self.sink = newWriter.sink } func setUp() async throws {} func tearDown() {} func run() async throws -> Int { for i in 0..<self.iterations { try await self.writer.yield(i) } return self.delegate.counter.load(ordering: .sequentiallyConsistent) } }
apache-2.0
d8fbaf5a1ea42094c019b85016a3f683
32.672727
111
0.645248
4.773196
false
false
false
false
GoogleCloudPlatform/ios-docs-samples
speech-to-speech/SpeechToSpeech/ViewController/SettingsViewController.swift
1
13768
// // Copyright 2019 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import MaterialComponents import MaterialComponents.MaterialTypographyScheme class SettingsViewController: UIViewController { var containerScheme = ApplicationScheme.shared.containerScheme var typographyScheme = MDCTypographyScheme() var selectedTransFrom = "" var selectedTransTo = "" var selectedSynthName = "" var selectedVoiceType = "" @IBOutlet weak var getStartedButton: MDCButton! let translateFromView: MDCTextField = { let address = MDCTextField() address.translatesAutoresizingMaskIntoConstraints = false address.autocapitalizationType = .words return address }() var translateFromController: MDCTextInputControllerFilled! let translateToView: MDCTextField = { let city = MDCTextField() city.translatesAutoresizingMaskIntoConstraints = false city.autocapitalizationType = .words return city }() var translateToController: MDCTextInputControllerFilled! let synthNameView: MDCTextField = { let state = MDCTextField() state.translatesAutoresizingMaskIntoConstraints = false state.autocapitalizationType = .allCharacters return state }() var synthNameController: MDCTextInputControllerFilled! let voiceTypeView: MDCTextField = { let zip = MDCTextField() zip.translatesAutoresizingMaskIntoConstraints = false return zip }() var voiceTypeController: MDCTextInputControllerFilled! var allTextFieldControllers = [MDCTextInputControllerFilled]() var appBar = MDCAppBar() lazy var alert : UIAlertController = { let alert = UIAlertController(title: ApplicationConstants.tokenFetchingAlertTitle, message: ApplicationConstants.tokenFetchingAlertMessage, preferredStyle: .alert) return alert }() required init?(coder aDecoder: NSCoder) { translateFromController = MDCTextInputControllerFilled(textInput: translateFromView) translateToController = MDCTextInputControllerFilled(textInput: translateToView) synthNameController = MDCTextInputControllerFilled(textInput: synthNameView) voiceTypeController = MDCTextInputControllerFilled(textInput: voiceTypeView) super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.view.tintColor = .black self.view.backgroundColor = ApplicationScheme.shared.colorScheme.surfaceColor self.title = ApplicationConstants.SettingsScreenTtitle NotificationCenter.default.addObserver(self, selector: #selector(dismissAlert), name: NSNotification.Name(ApplicationConstants.tokenReceived), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(presentAlert), name: NSNotification.Name(ApplicationConstants.retreivingToken), object: nil) setUpNavigationBarAndItems() if let userPreference = UserDefaults.standard.value(forKey: ApplicationConstants.useerLanguagePreferences) as? [String: String] { selectedTransFrom = userPreference[ApplicationConstants.selectedTransFrom] ?? "" selectedTransTo = userPreference[ApplicationConstants.selectedTransTo] ?? "" selectedSynthName = userPreference[ApplicationConstants.selectedSynthName] ?? "" selectedVoiceType = userPreference[ApplicationConstants.selectedVoiceType] ?? "" translateFromView.text = selectedTransFrom translateToView.text = selectedTransTo synthNameView.text = selectedSynthName voiceTypeView.text = selectedVoiceType } setupTextFields() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let appD = UIApplication.shared.delegate as? AppDelegate, appD.voiceLists?.isEmpty ?? true { presentAlert() appD.fetchVoiceList() NotificationCenter.default.addObserver(self, selector: #selector(dismissAlert), name: NSNotification.Name("FetchVoiceList"), object: nil) } } @objc func presentAlert() { //Showing the alert until token is received if alert.isViewLoaded == false { self.present(alert, animated: true, completion: nil) } } @objc func dismissAlert() { alert.dismiss(animated: true, completion: nil) } func setUpNavigationBarAndItems() { //Initialize and add AppBar self.addChild(appBar.headerViewController) appBar.addSubviewsToParent() MDCAppBarColorThemer.applySemanticColorScheme(ApplicationScheme.shared.colorScheme, to:self.appBar) } func style(textInputController:MDCTextInputControllerFilled) { textInputController.applyTheme(withScheme: containerScheme) MDCContainedButtonThemer.applyScheme(ApplicationScheme.shared.buttonScheme, to: getStartedButton) } func setupTextFields() { view.addSubview(translateFromView) translateFromView.delegate = self translateFromController.placeholderText = ApplicationConstants.translateFromPlaceholder allTextFieldControllers.append(translateFromController) view.addSubview(translateToView) translateToView.delegate = self translateToController.placeholderText = ApplicationConstants.translateToPlaceholder allTextFieldControllers.append(translateToController) view.addSubview(synthNameView) synthNameView.delegate = self synthNameController.placeholderText = ApplicationConstants.synthNamePlaceholder allTextFieldControllers.append(synthNameController) view.addSubview(voiceTypeView) voiceTypeView.delegate = self voiceTypeController.placeholderText = ApplicationConstants.voiceTypePlaceholder allTextFieldControllers.append(voiceTypeController) var tag = 0 for controller in allTextFieldControllers { guard let textField = controller.textInput as? MDCTextField else { continue } style(textInputController: controller); textField.tag = tag tag += 1 } if selectedVoiceType == "Default" { voiceTypeView.textColor = .gray } let views = [ "translateFromView": translateFromView, "translateToView": translateToView, "synthNameView": synthNameView, "voiceTypeView": voiceTypeView ] var constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[translateFromView]-[translateToView]-[synthNameView]-[voiceTypeView]", options: [.alignAllLeading, .alignAllTrailing], metrics: nil, views: views) constraints += [NSLayoutConstraint(item: translateFromView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0)] constraints += [NSLayoutConstraint(item: translateFromView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0)] constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[translateFromView]|", options: [], metrics: nil, views: views) constraints += [NSLayoutConstraint(item: translateFromView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .topMargin, multiplier: 1, constant: 80)] NSLayoutConstraint.activate(constraints) self.allTextFieldControllers.forEach({ (controller) in controller.isFloatingEnabled = true }) } @IBAction func getStarted(_ sender: Any) { print("selectedTransFrom: \(selectedTransFrom)") print("selectedTransTo: \(selectedTransTo)") print("selectedVoiceType: \(selectedVoiceType)") print("selectedSynthName: \(selectedSynthName)") if selectedTransFrom.isEmpty || selectedTransTo.isEmpty || selectedVoiceType.isEmpty || selectedSynthName.isEmpty { let alertVC = UIAlertController(title: "Infomation needed", message: "Please fill all the fields", preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "OK", style: .default)) present(alertVC, animated: true) return } UserDefaults.standard.set([ApplicationConstants.selectedTransFrom: selectedTransFrom, ApplicationConstants.selectedTransTo: selectedTransTo, ApplicationConstants.selectedSynthName: selectedSynthName, ApplicationConstants.selectedVoiceType : selectedVoiceType], forKey: ApplicationConstants.useerLanguagePreferences) if let speechVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SpeechViewController") as? SpeechViewController { navigationController?.pushViewController(speechVC, animated: true) } } func thirtyOptions(optionsType: OptionsType, completionHandler: @escaping (MDCActionSheetAction) -> Void) -> MDCActionSheetController { let actionSheet = MDCActionSheetController(title: optionsType.getTitle(), message: optionsType.getMessage()) for i in optionsType.getOptions(selectedTransTo: selectedTransTo) { let action = MDCActionSheetAction(title: i, image: nil, handler: completionHandler) actionSheet.addAction(action) } return actionSheet } } extension SettingsViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { let index = textField.tag if let optionType = OptionsType(rawValue: index) { if optionType == .synthName || optionType == .voiceType { if self.selectedTransTo.isEmpty { self.showNoTranslateToError() return false } } let actionSheet = thirtyOptions(optionsType: optionType, completionHandler: {action in switch optionType { case .translateFrom: self.selectedTransFrom = action.title case .translateTo: self.selectedTransTo = action.title let synthNames = OptionsType.synthName.getOptions(selectedTransTo: self.selectedTransTo)//optionType.synthName.getOptions(selectedTransTo: self.selectedTransTo) self.selectedSynthName = synthNames.contains("Wavenet") ? "Wavenet" : "Standard" self.selectedVoiceType = "Default" self.synthNameView.text = self.selectedSynthName self.voiceTypeView.text = self.selectedVoiceType self.voiceTypeView.textColor = .gray case .synthName: self.selectedSynthName = action.title case .voiceType: self.selectedVoiceType = action.title self.voiceTypeView.textColor = self.synthNameView.textColor } textField.text = action.title }) present(actionSheet, animated: true, completion: nil) } return false } func showNoTranslateToError() { let alertVC = UIAlertController(title: "Information needed", message: "Please select translate to first", preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: "OK", style: .default)) present(alertVC, animated: true) } } enum OptionsType: Int { case translateFrom = 0, translateTo, synthName, voiceType func getTitle() -> String { switch self { case .translateFrom: return "Translate from" case .translateTo: return "Translate to" case .synthName: return "Synthesis name" case .voiceType: return "Voice type" } } func getMessage() -> String { switch self { case .translateFrom: return "Choose one option for Translate from" case .translateTo: return "Choose one option for Translate to" case .synthName: return "Choose one option for Synthesis name" case .voiceType: return "Choose one option for Voice type" } } func getOptions(selectedTransTo: String = "") -> [String] { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate, let voiceList = appDelegate.voiceLists else { return [] } switch self { case .translateFrom, .translateTo: let from = voiceList.map { (formattedVoice) -> String in return formattedVoice.languageName } return from case .synthName: let synthName = voiceList.filter { return $0.languageName == selectedTransTo } if let synthesis = synthName.first { return synthesis.synthesisName } return [] case .voiceType: let synthName = voiceList.filter { return $0.languageName == selectedTransTo } if let synthesis = synthName.first { return synthesis.synthesisGender } return [] } } }
apache-2.0
c3f9e3ab7ea49e19ab965ad87e064eec
39.613569
319
0.679474
5.739058
false
false
false
false
faimin/Tropos
Sources/Tropos/ViewControllers/WebViewController.swift
2
1323
import UIKit class WebViewController: UIViewController, UIWebViewDelegate { @IBOutlet var webView: UIWebView! @objc var url = URL(string: "about:blank")! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) webView.loadRequest(URLRequest(url: url)) webView.scrollView.contentInset = UIEdgeInsets( top: 20.0, left: 20.0, bottom: 20.0, right: 20.0 ) } @IBAction func share(_ sender: UIBarButtonItem) { let activityViewController = UIActivityViewController( activityItems: [url], applicationActivities: nil ) present(activityViewController, animated: true, completion: nil) } func webViewDidStartLoad(_ webView: UIWebView) { navigationItem.rightBarButtonItem = .activityIndicatorBarButtonItem() } func webViewDidFinishLoad(_ webView: UIWebView) { navigationItem.rightBarButtonItem = nil } } extension UIBarButtonItem { @objc static func activityIndicatorBarButtonItem() -> UIBarButtonItem { let activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white) activityIndicatorView.startAnimating() return UIBarButtonItem(customView: activityIndicatorView) } }
mit
9ca286e2800665d3e72aa2f1bfcc105b
30.5
91
0.674981
5.752174
false
false
false
false
haijianhuo/PhotoBox
PhotoBox/Helpers.swift
1
1333
// // Helper.swift // PhotoBox // // Created by Haijian Huo on 3/31/17. // Copyright © 2017 Haijian Huo. All rights reserved. // import UIKit class Helpers: NSObject { class func documentDirectoryURL() -> URL { do { let searchPathDirectory = FileManager.SearchPathDirectory.documentDirectory return try FileManager.default.url(for: searchPathDirectory, in: .userDomainMask, appropriateFor: nil, create: true) } catch { fatalError("*** Error finding default directory: \(error)") } } class func timeId() -> String { return String(format: "%0.0f", Date().timeIntervalSince1970) } class func resizeImage(_ image: UIImage, ratio: CGFloat) -> UIImage { let newWidth = image.size.width * ratio let newHeight = image.size.height * ratio let newSize = CGSize(width: newWidth, height: newHeight) UIGraphicsBeginImageContext(newSize) image.draw(in: CGRect(origin: CGPoint(x: 0, y :0), size: newSize)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
mit
c79142b1e881cefcd8a00f0dc45efc9d
30.714286
87
0.567568
5.182879
false
false
false
false
AlexRamey/mbird-iOS
iOS Client/PodcastsController/PodcastDetailViewController.swift
1
12442
// // PodcastDetailViewController.swift // iOS Client // // Created by Jonathan Witten on 12/21/17. // Copyright © 2017 Mockingbird. All rights reserved. // import UIKit import AVKit protocol PodcastDetailHandler: class { func dismissDetail() } class PodcastDetailViewController: UIViewController, PodcastPlayerSubscriber { @IBOutlet weak var durationSlider: UISlider! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var durationLabel: UILabel! @IBOutlet weak var totalDurationLabel: UILabel! @IBOutlet weak var imageWidthConstraint: NSLayoutConstraint! @IBOutlet weak var imageHeightConstraint: NSLayoutConstraint! @IBOutlet weak var backgroundImageView: UIImageView! @IBOutlet weak var rewindButton: UIButton! @IBOutlet weak var fastforwardButton: UIButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var currentProgress: Double = 0.0 var totalDuration: Double = 0.0 var fullImageSize: CGFloat = 0.0 var isPlaying: Bool = false var player: PodcastPlayer! var selectedPodcast: Podcast! var saved: Bool = false var timeFormatter: DateComponentsFormatter! var podcastStore = MBPodcastsStore() var uninstaller: Uninstaller? weak var handler: PodcastDetailHandler? static func instantiateFromStoryboard(podcast: Podcast, player: PodcastPlayer, uninstaller: Uninstaller, handler: PodcastDetailHandler) -> PodcastDetailViewController { // swiftlint:disable force_cast let detailVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PodcastDetailViewController") as! PodcastDetailViewController // swiftlint:enable force_cast detailVC.selectedPodcast = podcast detailVC.player = player detailVC.handler = handler let timeFormatter = DateComponentsFormatter() timeFormatter.unitsStyle = .positional timeFormatter.allowedUnits = [ .hour, .minute, .second ] timeFormatter.zeroFormattingBehavior = [ .pad ] detailVC.timeFormatter = timeFormatter detailVC.uninstaller = uninstaller return detailVC } override func viewDidLoad() { super.viewDidLoad() titleLabel.text = self.selectedPodcast.title let imageName = self.selectedPodcast.image imageView.image = UIImage(named: imageName) backgroundImageView.image = UIImage(named: imageName) self.navigationItem.title = selectedPodcast.feed.shortTitle self.titleLabel.font = UIFont(name: "IowanOldStyle-Bold", size: 20) durationSlider.addTarget(self, action: #selector(onSeek(slider:event:)), for: .valueChanged) durationSlider.setValue(0.0, animated: false) // Sets the nav bar to be transparent self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.view.backgroundColor = UIColor.clear self.navigationController?.navigationBar.backgroundColor = UIColor.clear fullImageSize = view.bounds.height * 0.25 self.imageWidthConstraint.constant = fullImageSize self.imageHeightConstraint.constant = fullImageSize // if our podcast is already selected, then immediately grab the progress values if self.player.currentlyPlayingPodcast?.guid == self.selectedPodcast.guid { self.currentProgress = self.player.getCurrentProgress() self.totalDuration = self.player.getTotalDuration() self.updateCurrentDuration() // if the podcast is already playing, then update the UI to reflect that if self.player.player.rate != 0.0 { self.isPlaying = true self.playPauseButton.setImage(#imageLiteral(resourceName: "pause-bars"), for: .normal) self.imageWidthConstraint.constant = fullImageSize * 0.75 self.imageHeightConstraint.constant = fullImageSize * 0.75 } } else { // new selection! self.activityIndicator.startAnimating() self.playPauseButton.isHidden = true self.rewindButton.isHidden = true self.fastforwardButton.isHidden = true self.player.playPodcast(self.selectedPodcast, completion: { self.activityIndicator.stopAnimating() self.playPauseButton.isHidden = false self.rewindButton.isHidden = false self.fastforwardButton.isHidden = false }) } self.saved = podcastStore.containsSavedPodcast(self.selectedPodcast) configureBarButtonItems(downloaded: self.saved) self.view.layoutIfNeeded() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.player.subscribe(self) self.imageView.layer.shadowPath = UIBezierPath(rect: self.imageView.bounds).cgPath self.imageView.layer.shadowRadius = 20 self.imageView.layer.shadowOpacity = 0.4 self.imageView.layer.shadowOffset = CGSize(width: -5, height: -5) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.player.unsubscribe(self) } @IBAction func pressPlayPause(_ sender: Any) { self.player.togglePlayPause() } @IBAction func pressFastForward(_ sender: Any) { player?.seek(relative: 15) } @IBAction func pressRewind(_ sender: Any) { player?.seek(relative: -15) } @objc func onSeek(slider: UISlider, event: UIEvent) { if let touchEvent = event.allTouches?.first { let secondToSeekTo = Double(slider.value) * (self.totalDuration) switch touchEvent.phase { case .moved: self.currentProgress = secondToSeekTo self.updateCurrentDuration() case .ended: self.player.seek(to: secondToSeekTo) default: break } } } @IBAction func pressDownloadButton(_ sender: Any) { if saved { removePodcast() } else { downloadPodcast() } } func animateImage(size: CGSize, duration: CFTimeInterval) { var shadowRect = imageView.bounds let fromRect = CGRect(x: shadowRect.origin.x, y: shadowRect.origin.y, width: shadowRect.width + 10, height: shadowRect.height + 10) shadowRect.size = CGSize(width: size.width + 10, height: size.height + 10) let shadowAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.shadowPath)) shadowAnimation.fromValue = UIBezierPath(rect: fromRect).cgPath shadowAnimation.toValue = UIBezierPath(rect: shadowRect).cgPath shadowAnimation.isRemovedOnCompletion = false shadowAnimation.fillMode = kCAFillModeForwards shadowAnimation.duration = duration shadowAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) self.imageWidthConstraint.constant = size.width self.imageHeightConstraint.constant = size.height self.imageView.layer.add(shadowAnimation, forKey: #keyPath(CALayer.shadowPath)) UIView.animate(withDuration: duration) { self.view.layoutIfNeeded() } } private func updateCurrentDuration() { self.timeFormatter.allowedUnits = self.totalDuration >= Double(3600) ? [.hour, .minute, .second] : [.minute, .second] self.durationLabel.text = timeFormatter.string(from: self.currentProgress) self.totalDurationLabel.text = timeFormatter.string(from: self.totalDuration) if self.totalDuration > 0.0 { self.durationSlider.setValue(Float(self.currentProgress/self.totalDuration), animated: true) } } private func configureBarButtonItems(downloaded: Bool) { self.navigationItem.rightBarButtonItems = [getDownloadBarButton(downloaded: downloaded), getShareBarButton()] } private func getDownloadBarButton(downloaded: Bool) -> UIBarButtonItem { return UIBarButtonItem(image: downloaded ? UIImage(named: "download-done") : UIImage(named: "add"), style: .done, target: self, action: downloaded ? #selector(PodcastDetailViewController.removePodcast) : #selector(PodcastDetailViewController.downloadPodcast)) } private func getShareBarButton() -> UIBarButtonItem { // return UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(PodcastDetailViewController.sharePodcast)) return UIBarButtonItem(image: UIImage(named: "share-button"), style: .plain, target: self, action: #selector(PodcastDetailViewController.sharePodcast)) } @objc private func removePodcast() { guard let title = self.selectedPodcast.title else { return } _ = uninstaller?.uninstall(podcastId: title).then { uninstalled in self.saved = !uninstalled } } @objc private func downloadPodcast() { guard let path = self.selectedPodcast.guid, let title = self.selectedPodcast.title, let url = URL(string: path) else { return } _ = MBClient().getPodcast(url: url).then { podcast in return self.podcastStore.savePodcastData(data: podcast, path: title) }.then { _ -> Void in self.saved = true self.configureBarButtonItems(downloaded: true) } } // MARK: - Podcast Player Subscriber func notify(currentPodcastGuid: String?, currentProgress: Double, totalDuration: Double, isPlaying: Bool, isCanceled: Bool) { DispatchQueue.main.async { // disregard this notify unless it's for our podcast guard self.selectedPodcast.guid == currentPodcastGuid else { return } guard !isCanceled else { self.handler?.dismissDetail() return } self.currentProgress = currentProgress self.totalDuration = totalDuration self.updateCurrentDuration() if isPlaying != self.isPlaying { if isPlaying { // just turned on self.playPauseButton.setImage(#imageLiteral(resourceName: "pause-bars"), for: .normal) self.animateImage(size: CGSize(width: self.fullImageSize * 0.75, height: self.fullImageSize * 0.75), duration: 0.6) } else { // just turned off self.playPauseButton.setImage(#imageLiteral(resourceName: "play-arrow"), for: .normal) self.animateImage(size: CGSize(width: self.fullImageSize, height: self.fullImageSize), duration: 0.6) } } self.isPlaying = isPlaying } } @objc func sharePodcast(sender: Any) { // set up activity view controller let activityViewController = UIActivityViewController(activityItems: [ "\(selectedPodcast.feed.title): ", selectedPodcast.title ?? "", selectedPodcast.guid ?? "" ], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash // exclude some activity types from the list (optional) activityViewController.excludedActivityTypes = [ .airDrop, .assignToContact, .openInIBooks, .postToFlickr, .postToVimeo, .print, .saveToCameraRoll ] // present the view controller self.present(activityViewController, animated: true, completion: nil) } }
mit
076b47a5e785dfb32ae21564cd9b8d5e
42.197917
200
0.641347
5.367127
false
false
false
false
chris-wood/reveiller
reveiller/Pods/SwiftCharts/SwiftCharts/AxisValues/ChartAxisValueFloat.swift
6
1621
// // ChartAxisValueFloat.swift // swift_charts // // Created by ischuetz on 15/03/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit //@availability(*, deprecated=0.2.5, message="use ChartAxisValueDouble instead") /** DEPRECATED use ChartAxisValueDouble instead Above annotation causes warning inside this file and it was not possible to supress (tried http://stackoverflow.com/a/6921972/930450 etc.) */ public class ChartAxisValueFloat: ChartAxisValue { public let formatter: NSNumberFormatter let labelSettings: ChartLabelSettings public var float: CGFloat { return CGFloat(self.scalar) } override public var text: String { return self.formatter.stringFromNumber(self.float)! } public init(_ float: CGFloat, formatter: NSNumberFormatter = ChartAxisValueFloat.defaultFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) { self.formatter = formatter self.labelSettings = labelSettings super.init(scalar: Double(float)) } override public var labels: [ChartAxisLabel] { let axisLabel = ChartAxisLabel(text: self.text, settings: self.labelSettings) return [axisLabel] } override public func copy(scalar: Double) -> ChartAxisValueFloat { return ChartAxisValueFloat(CGFloat(scalar), formatter: self.formatter, labelSettings: self.labelSettings) } static var defaultFormatter: NSNumberFormatter = { let formatter = NSNumberFormatter() formatter.maximumFractionDigits = 2 return formatter }() }
mit
0fab8417db98243d448988c06f2e7358
31.42
162
0.70327
5.129747
false
false
false
false
LYM-mg/DemoTest
indexView/indexView/One/加密相关/加密算法/加密/NSData+Extension.swift
1
7392
// // NSData+Extension.swift // indexView // // Created by i-Techsys.com on 17/3/21. // Copyright © 2017年 i-Techsys. All rights reserved. // import UIKit // MARK: - 加密 AES/AES128/DES/DES3/CAST/RC2/RC4/Blowfish...... /** 需在桥接文件导入头文件 ,因为C语言的库 * #import <CommonCrypto/CommonDigest.h> * #import <CommonCrypto/CommonCrypto.h> */ enum CryptoAlgorithm { /// 加密的枚举选项 AES/AES128/DES/DES3/CAST/RC2/RC4/Blowfish...... case AES, AES128, DES, DES3, CAST, RC2,RC4, Blowfish var algorithm: CCAlgorithm { var result: UInt32 = 0 switch self { case .AES: result = UInt32(kCCAlgorithmAES) case .AES128: result = UInt32(kCCAlgorithmAES128) case .DES: result = UInt32(kCCAlgorithmDES) case .DES3: result = UInt32(kCCAlgorithm3DES) case .CAST: result = UInt32(kCCAlgorithmCAST) case .RC2: result = UInt32(kCCAlgorithmRC2) case .RC4: result = UInt32(kCCAlgorithmRC4) case .Blowfish: result = UInt32(kCCAlgorithmBlowfish) } return CCAlgorithm(result) } var keyLength: Int { var result: Int = 0 switch self { case .AES: result = kCCKeySizeAES128 case .AES128: result = kCCKeySizeAES256 case .DES: result = kCCKeySizeDES case .DES3: result = kCCKeySize3DES case .CAST: result = kCCKeySizeMaxCAST case .RC2: result = kCCKeySizeMaxRC2 case .RC4: result = kCCKeySizeMaxRC4 case .Blowfish: result = kCCKeySizeMaxBlowfish } return Int(result) } var cryptLength: Int { var result: Int = 0 switch self { case .AES: result = kCCKeySizeAES128 case .AES128: result = kCCBlockSizeAES128 case .DES: result = kCCBlockSizeDES case .DES3: result = kCCBlockSize3DES case .CAST: result = kCCBlockSizeCAST case .RC2: result = kCCBlockSizeRC2 case .RC4: result = kCCBlockSizeRC2 case .Blowfish: result = kCCBlockSizeBlowfish } return Int(result) } } // MARK: - 加密扩展NSData extension NSData { /* 加密 - parameter algorithm: 加密方式 - parameter keyData: 加密key - return NSData: 加密后的数据 可选值 */ func enCrypt(algorithm: CryptoAlgorithm, keyData:NSData) -> NSData? { return crypt(algorithm: algorithm, operation: CCOperation(kCCEncrypt), keyData: keyData) } /* 解密 - parameter algorithm: 解密方式 - parameter keyData: 解密key - return NSData: 解密后的数据 可选值 */ func deCrypt(algorithm: CryptoAlgorithm, keyData:NSData) -> NSData? { return crypt(algorithm: algorithm, operation: CCOperation(kCCDecrypt), keyData: keyData) } /* 解密和解密方法的抽取的封装方法 - parameter algorithm: 何种加密方式 - parameter operation: 加密和解密 - parameter keyData: 加密key - return NSData: 解密后的数据 可选值 */ func crypt(algorithm: CryptoAlgorithm, operation:CCOperation, keyData:NSData) -> NSData? { let keyBytes = keyData.bytes let keyLength = Int(algorithm.keyLength) let dataLength = self.length let dataBytes = self.bytes let cryptLength = Int(dataLength + algorithm.cryptLength) let cryptPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: cryptLength) let algoritm: CCAlgorithm = CCAlgorithm(algorithm.algorithm) let option: CCOptions = CCOptions(kCCOptionECBMode + kCCOptionPKCS7Padding) let numBytesEncrypted = UnsafeMutablePointer<Int>.allocate(capacity: 1) numBytesEncrypted.initialize(to: 0) let cryptStatus = CCCrypt(operation, algoritm, option, keyBytes, keyLength, nil, dataBytes, dataLength, cryptPointer, cryptLength, numBytesEncrypted) if CCStatus(cryptStatus) == CCStatus(kCCSuccess) { let len = Int(numBytesEncrypted.pointee) let data:NSData = NSData(bytesNoCopy: cryptPointer, length: len) numBytesEncrypted.deallocate() return data } else { numBytesEncrypted.deallocate() cryptPointer.deallocate() return nil } } } // MARK: - Data Data打印出来是16或者32 bytes,打印需转成NSData类型打印结果比较直观 // MARK: - data extension Data { /* 加密 - parameter algorithm: 加密方式 - parameter keyData: 加密key - return NSData: 加密后的数据 可选值 */ mutating func enCrypt(algorithm: CryptoAlgorithm, keyData:Data) -> Data? { return crypt(algorithm: algorithm, operation: CCOperation(kCCEncrypt), keyData: keyData) } /* 解密 - parameter algorithm: 解密方式 - parameter keyData: 解密key - return NSData: 解密后的数据 可选值 */ mutating func deCrypt(algorithm: CryptoAlgorithm, keyData:Data) -> Data? { return crypt(algorithm: algorithm, operation: CCOperation(kCCDecrypt), keyData: keyData) } /* 解密和解密方法的抽取的封装方法 - parameter algorithm: 何种加密方式 - parameter operation: 加密和解密 - parameter keyData: 加密key - return NSData: 解密后的数据 可选值 */ mutating func crypt(algorithm: CryptoAlgorithm, operation:CCOperation, keyData: Data) -> Data? { let keyLength = Int(algorithm.keyLength) let dataLength = self.count let cryptLength = Int(dataLength+algorithm.cryptLength) let cryptPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: cryptLength) let algoritm: CCAlgorithm = CCAlgorithm(algorithm.algorithm) let option: CCOptions = CCOptions(kCCOptionECBMode + kCCOptionPKCS7Padding) let numBytesEncrypted = UnsafeMutablePointer<Int>.allocate(capacity: 1) numBytesEncrypted.initialize(to: 0) var keyBytes: UnsafePointer<Int8>? keyData.withUnsafeBytes {(bytes: UnsafePointer<Int8>)->Void in keyBytes = bytes } var dataBytes: UnsafePointer<Int8>? self.withUnsafeBytes {(bytes: UnsafePointer<CChar>)->Void in // print(bytes) dataBytes = bytes } let cryptStatus = CCCrypt(operation, algoritm, option, keyBytes!, keyLength, nil, dataBytes!, dataLength, cryptPointer, cryptLength, numBytesEncrypted) if CCStatus(cryptStatus) == CCStatus(kCCSuccess) { let len = Int(numBytesEncrypted.pointee) let data = Data.init(bytes: cryptPointer, count: len) numBytesEncrypted.deallocate() return data } else { numBytesEncrypted.deallocate() cryptPointer.deallocate() return nil } } }
mit
94fb46a96e3b02ce55e03bea3d263ab6
33.648515
159
0.597657
4.669113
false
false
false
false
tluquet3/MonTennis
MonTennis/Base.lproj/TabBarController.swift
1
8732
// // TabBarController.swift // MonTennis // // Created by Thomas Luquet on 02/06/2015. // Copyright (c) 2015 Thomas Luquet. All rights reserved. // import UIKit import CoreData var barCtrl : TabBarController! class TabBarController: UITabBarController { internal var user : Utilisateur! override func viewDidLoad() { super.viewDidLoad() // Change the appearance of the tab bar UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], forState:.Normal) UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColorFromRGB(0x007AFF)], forState:.Selected) //Change the color of the tab bar icons to white for item in self.tabBar.items as [UITabBarItem]! { if let image = item.image { item.image = image.imageWithColor(UIColor.whiteColor()).imageWithRenderingMode(.AlwaysOriginal) } } barCtrl = self } override func viewWillAppear(animated: Bool) { // Load Profile from NSUserDefault let userData = NSUserDefaults.standardUserDefaults() if(userData.stringForKey("firstName") == nil){ userData.setObject(" ", forKey: "firstName") userData.setObject(" ", forKey: "lastName") userData.setBool(true, forKey: "sex") userData.setInteger(Classement(stringValue: "NC").value, forKey: "classement") userData.setObject(" ", forKey: "club") self.selectedIndex = 2 } user = Utilisateur(firstName: userData.stringForKey("firstName")!, lastName: userData.stringForKey("lastName")!, classement: Classement(value: userData.integerForKey("classement")), sex: userData.boolForKey("sex"),club: userData.stringForKey("club")!) // Load palmares data from CoreData let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! let fetchRequest = NSFetchRequest(entityName:"Match") do{ let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject] if let results = fetchedResults { user.viderPalmares() var match: Match for matchF in results{ match = Match(resultat: matchF.valueForKey("resultat") as! Bool, firstName: matchF.valueForKey("firstName") as! String, lastName: matchF.valueForKey("lastName") as! String, classement: Classement(value: matchF.valueForKey("classement") as! Int), bonus: matchF.valueForKey("bonus") as! Bool, coef: matchF.valueForKey("coef") as! Double, wo: matchF.valueForKey("wo") as! Bool) user.ajoutMatch(match) } } }catch { print("Could not fetch \(error)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Core Data internal func fillCoreData(){ //Update the coreData let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! let entity = NSEntityDescription.entityForName("Match", inManagedObjectContext: managedContext) for matchU in user.victoires{ let match = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) match.setValue(matchU.resultat, forKey: "resultat") match.setValue(matchU.firstName, forKey: "firstName") match.setValue(matchU.lastName, forKey: "lastName") match.setValue(matchU.wo, forKey: "wo") match.setValue(matchU.classement.value, forKey: "classement") match.setValue(matchU.bonus, forKey: "bonus") match.setValue(matchU.coef, forKey: "coef") match.setValue(matchU.score, forKey: "score") match.setValue(matchU.tournoi, forKey: "tournoi") } for matchU in user.defaites{ let match = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext) match.setValue(matchU.resultat, forKey: "resultat") match.setValue(matchU.firstName, forKey: "firstName") match.setValue(matchU.lastName, forKey: "lastName") match.setValue(matchU.wo, forKey: "wo") match.setValue(matchU.classement.value, forKey: "classement") match.setValue(matchU.bonus, forKey: "bonus") match.setValue(matchU.coef, forKey: "coef") match.setValue(matchU.score, forKey: "score") match.setValue(matchU.tournoi, forKey: "tournoi") } var error: NSError? do { try managedContext.save() } catch let error1 as NSError { error = error1 print("Could not save \(error), \(error?.userInfo)") } } internal func clearCoreData(){ let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! do{ let fetchRequest = NSFetchRequest(entityName:"Match") var fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject] if let results = fetchedResults { for matchF in results{ managedContext.deleteObject(matchF as NSManagedObject) } fetchedResults?.removeAll(keepCapacity: false) do { try managedContext.save() } catch _ { } } }catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } internal func getNSuserDefaults()->NSUserDefaults{ return NSUserDefaults.standardUserDefaults() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. }*/ func UIColorFromRGB(rgbValue: UInt) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } func actionSheetForFirstLogin() { let actionSheet: UIAlertController = UIAlertController(title: "the title", message: "the message", preferredStyle: .ActionSheet) let callActionHandler = { (action:UIAlertAction!) -> Void in let alertMessage = UIAlertController(title: action.title, message: "You chose an action", preferredStyle: .Alert) alertMessage.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(alertMessage, animated: true, completion: nil) } let action1: UIAlertAction = UIAlertAction(title: "action title 1", style: .Default, handler:callActionHandler) let action2: UIAlertAction = UIAlertAction(title: "action title 2", style: .Default, handler:callActionHandler) actionSheet.addAction(action1) actionSheet.addAction(action2) presentViewController(actionSheet, animated: true, completion:nil) } } extension UIImage { func imageWithColor(tintColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext()! as CGContextRef CGContextTranslateCTM(context, 0, self.size.height) CGContextScaleCTM(context, 1.0, -1.0); CGContextSetBlendMode(context, CGBlendMode.Normal) let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect CGContextClipToMask(context, rect, self.CGImage) tintColor.setFill() CGContextFillRect(context, rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext() return newImage } }
apache-2.0
9fdcdd1e3b738a800928f138348c271a
41.183575
394
0.623798
5.269765
false
false
false
false
wwq0327/iOS8Example
Diary/Diary/DiaryHelper.swift
1
3774
// // DiaryHelper.swift // Diary // // Created by wyatt on 15/6/14. // Copyright (c) 2015年 Wanqing Wang. All rights reserved. // import UIKit let defaultFont = "Wyue-GutiFangsong-NC" let screenRect = UIScreen.mainScreen().bounds let DiaryRed = UIColor(red: 192.0/255.0, green: 23.0/255.0, blue: 48.0/255.0, alpha: 1.0) let DiaryFont = UIFont(name: defaultFont, size: 18.0) as UIFont! let DiaryLocationFont = UIFont(name: defaultFont, size: 16.0) as UIFont! let DiaryTitleFont = UIFont(name: defaultFont, size: 18.0) as UIFont! // CoreData 数据库配置 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext! // storyboard identifiers struct StoryboardIdentifiers { static let diaryYearIdentifiers = "DiaryYearCollectionViewController" static let diaryMonthIdentifiers = "DiaryMonthDayCollectionViewController" static let diaryComposeViewController = "DiaryComposeViewController" static let diaryViewController = "DiaryViewController" } // colletioncell indetifiers struct CollectionCellIdetifiers { // home视图中的cell static let homeYearCellIdentifiers = "HomeYearCollectionViewCell" // 二级中cell static let diaryCellIdentifiers = "DiaryCollectionViewCell" } // 创建自定义按钮 func diaryButtonWith(#text: String, #fontSize: CGFloat, #width: CGFloat, #normalImageName: String, #highlightedImageName: String) -> UIButton { var button = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton button.frame = CGRectMake(0, 0, width, width) var font = UIFont(name: "Wyue-GutiFangsong-NC", size: fontSize) as UIFont! let textAttributes: [NSObject: AnyObject] = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.whiteColor()] var attributedText = NSAttributedString(string: text, attributes: textAttributes) button.setAttributedTitle(attributedText, forState: UIControlState.Normal) // 按钮的正常图片背景及高亮背景 button.setBackgroundImage(UIImage(named: normalImageName), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: highlightedImageName), forState: UIControlState.Highlighted) return button } // 将数字日期转换为中文的汉字日期 func numberToChinese(number: Int) -> String { var numbers = Array(String(number)) var finalString = "" for singleNumber in numbers { var string = singleNumberToChinese(singleNumber) finalString = "\(finalString)\(string)" } return finalString } // 带单位的中文数字 func numberToChineseWithUnit(number: Int) -> String { var numbers = Array(String(number)) var units = unitParser(numbers.count) var finalString = "" for (index, singleNumber) in enumerate(numbers) { var string = singleNumberToChinese(singleNumber) if (!(string == "零" && (index+1) == numbers.count)) { finalString = "\(finalString)\(string)\(units[index])" } } return finalString } func unitParser(unit: Int) -> [String] { var units = ["万", "千", "百", "十", ""].reverse() var sliceUnits: ArraySlice<String> = units[0..<(unit)].reverse() var final: [String] = Array(sliceUnits) return final } func singleNumberToChinese(number: Character) -> String { switch number { case "0": return "零" case "1": return "一" case "2": return "二" case "3": return "三" case "4": return "四" case "5": return "五" case "6": return "六" case "7": return "七" case "8": return "八" case "9": return "九" default: return "" } }
apache-2.0
59f56791546fdd05e23d5c2d9c5f7283
29.504202
143
0.683196
4.042316
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/Swiftz/Sources/Swiftz/Num.swift
3
9214
// // Num.swift // Swiftz // // Created by Maxwell Swadling on 3/06/2014. // Copyright (c) 2014-2016 Maxwell Swadling. All rights reserved. // #if SWIFT_PACKAGE import Swiftx #endif /// Numeric types. public protocol NumericType : Comparable { /// The null quantity. static var zero : Self { get } /// The singular quantity. static var one : Self { get } /// The magnitude of the quantity. var signum : Self { get } /// A quantity with the opposing magnitude of the receiver. var negate : Self { get } /// The quantity produced by adding the given quantity to the receiver. func plus(_ : Self) -> Self /// The quantity produced by subtracting the given quantity from the receiver. func minus(_ : Self) -> Self /// The quantity produced by multiplying the receiver by the given quantity. func times(_ : Self) -> Self } extension NumericType { public var signum : Self { if self == Self.zero { return Self.zero } else if self > Self.zero { return Self.one } else { return Self.one.negate } } public var absoluteValue : Self { return (self.signum >= Self.zero) ? self : self.negate } } extension Int : NumericType { public static var zero : Int { return 0 } public static var one : Int { return 1 } public var negate : Int { return -self } public func plus(_ other : Int) -> Int { return self + other } public func minus(_ other : Int) -> Int { return self - other } public func times(_ other : Int) -> Int { return self * other } } extension Int8 : NumericType { public static var zero : Int8 { return 0 } public static var one : Int8 { return 1 } public var negate : Int8 { return -self } public func plus(_ other : Int8) -> Int8 { return self + other } public func minus(_ other : Int8) -> Int8 { return self - other } public func times(_ other : Int8) -> Int8 { return self * other } } extension Int16 : NumericType { public static var zero : Int16 { return 0 } public static var one : Int16 { return 1 } public var negate : Int16 { return -self } public func plus(_ other : Int16) -> Int16 { return self + other } public func minus(_ other : Int16) -> Int16 { return self - other } public func times(_ other : Int16) -> Int16 { return self * other } } extension Int32 : NumericType { public static var zero : Int32 { return 0 } public static var one : Int32 { return 1 } public var negate : Int32 { return -self } public func plus(_ other : Int32) -> Int32 { return self + other } public func minus(_ other : Int32) -> Int32 { return self - other } public func times(_ other : Int32) -> Int32 { return self * other } } extension Int64 : NumericType { public static var zero : Int64 { return 0 } public static var one : Int64 { return 1 } public var negate : Int64 { return -self } public func plus(_ other : Int64) -> Int64 { return self + other } public func minus(_ other : Int64) -> Int64 { return self - other } public func times(_ other : Int64) -> Int64 { return self * other } } extension UInt : NumericType { public static var zero : UInt { return 0 } public static var one : UInt { return 1 } public var negate : UInt { return undefined() } public func plus(_ other : UInt) -> UInt { return self + other } public func minus(_ other : UInt) -> UInt { return self - other } public func times(_ other : UInt) -> UInt { return self * other } } extension UInt8 : NumericType { public static var zero : UInt8 { return 0 } public static var one : UInt8 { return 1 } public var negate : UInt8 { return undefined() } public func plus(_ other : UInt8) -> UInt8 { return self + other } public func minus(_ other : UInt8) -> UInt8 { return self - other } public func times(_ other : UInt8) -> UInt8 { return self * other } } extension UInt16 : NumericType { public static var zero : UInt16 { return 0 } public static var one : UInt16 { return 1 } public var negate : UInt16 { return undefined() } public func plus(_ other : UInt16) -> UInt16 { return self + other } public func minus(_ other : UInt16) -> UInt16 { return self - other } public func times(_ other : UInt16) -> UInt16 { return self * other } } extension UInt32 : NumericType { public static var zero : UInt32 { return 0 } public static var one : UInt32 { return 1 } public var negate : UInt32 { return undefined() } public func plus(_ other : UInt32) -> UInt32 { return self + other } public func minus(_ other : UInt32) -> UInt32 { return self - other } public func times(_ other : UInt32) -> UInt32 { return self * other } } extension UInt64 : NumericType { public static var zero : UInt64 { return 0 } public static var one : UInt64 { return 1 } public var negate : UInt64 { return undefined() } public func plus(_ other : UInt64) -> UInt64 { return self + other } public func minus(_ other : UInt64) -> UInt64 { return self - other } public func times(_ other : UInt64) -> UInt64 { return self * other } } /// Numeric types that support full-precision `Rational` conversions. public protocol RealType : NumericType { var toRational : Rational { get } } extension Int : RealType { public var toRational : Rational { return Rational(numerator: self, denominator: 1) } } extension Int8 : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } extension Int16 : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } extension Int32 : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } extension Int64 : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } extension UInt : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } extension UInt8 : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } extension UInt16 : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } extension UInt32 : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } extension UInt64 : RealType { public var toRational : Rational { return Rational(numerator: Int(self), denominator: 1) } } /// Numeric types that support division. public protocol IntegralType : RealType { /// Simultaneous quotient and remainder. func quotientRemainder(_ : Self) -> (quotient : Self, remainder : Self) } extension IntegralType { public func quotient(_ d : Self) -> Self { return self.quotientRemainder(d).quotient } public func remainder(_ d : Self) -> Self { return self.quotientRemainder(d).remainder } public func divide(_ d : Self) -> Self { return self.divMod(d).quotient } public func mod(_ d : Self) -> Self { return self.divMod(d).modulus } public func divMod(_ d : Self) -> (quotient : Self, modulus : Self) { let (q, r) = self.quotientRemainder(d) if r.signum == d.signum.negate { return (q.minus(Self.one), r.plus(d)) } return (q, r) } /// Returns the least common multiple of the receiver and a given quantity. public func leastCommonMultiple(_ other : Self) -> Self { if self == Self.zero || other == Self.zero { return Self.zero } return self.quotient(self.greatestCommonDivisor(other)).times(other).absoluteValue } /// Returns the greatest common divisor of the receiver and a given quantity. /// /// Unrolled version of tranditionally recursive Euclidean Division algorithm. public func greatestCommonDivisor(_ other : Self) -> Self { var a = self var b = other while b != Self.zero { let v = b b = a.mod(b) a = v } return a } } extension Int : IntegralType { public func quotientRemainder(_ d : Int) -> (quotient : Int, remainder : Int) { return (self / d, self % d) } } extension Int8 : IntegralType { public func quotientRemainder(_ d : Int8) -> (quotient : Int8, remainder : Int8) { return (self / d, self % d) } } extension Int16 : IntegralType { public func quotientRemainder(_ d : Int16) -> (quotient : Int16, remainder : Int16) { return (self / d, self % d) } } extension Int32 : IntegralType { public func quotientRemainder(_ d : Int32) -> (quotient : Int32, remainder : Int32) { return (self / d, self % d) } } extension Int64 : IntegralType { public func quotientRemainder(_ d : Int64) -> (quotient : Int64, remainder : Int64) { return (self / d, self % d) } } extension UInt : IntegralType { public func quotientRemainder(_ d : UInt) -> (quotient : UInt, remainder : UInt) { return (self / d, self % d) } } extension UInt8 : IntegralType { public func quotientRemainder(_ d : UInt8) -> (quotient : UInt8, remainder : UInt8) { return (self / d, self % d) } } extension UInt16 : IntegralType { public func quotientRemainder(_ d : UInt16) -> (quotient : UInt16, remainder : UInt16) { return (self / d, self % d) } } extension UInt32 : IntegralType { public func quotientRemainder(_ d : UInt32) -> (quotient : UInt32, remainder : UInt32) { return (self / d, self % d) } } extension UInt64 : IntegralType { public func quotientRemainder(_ d : UInt64) -> (quotient : UInt64, remainder : UInt64) { return (self / d, self % d) } }
apache-2.0
54edd7ea9003020aa5f404e69284aa2d
32.384058
119
0.680269
3.541122
false
false
false
false
nodes-ios/NStackSDK
NStackSDK/NStackSDK/Classes/Other/SectionKeyHelper.swift
1
882
// // SectionKeyHelper.swift // NStackSDK // // Created by Nicolai Harbo on 01/08/2019. // Copyright © 2019 Nodes ApS. All rights reserved. // import Foundation struct SectionKeyHelper { static func split(_ sectionAndKey: String) -> (section: String, key: String)? { let seperated = sectionAndKey.split(separator: ".") if seperated.count == 2 { let sect = seperated[0] == "defaultSection" ? "default" : seperated[0] return ("\(sect)", "\(seperated[1])") } return nil } static func combine(section: String, key: String) -> String { return "\(section).\(key)" } static func transform(_ sectionAndKey: String) -> TranslationIdentifier? { guard let tuple = split(sectionAndKey) else { return nil } return TranslationIdentifier(section: tuple.section, key: tuple.key) } }
mit
021071dae0c8a3284d4ab1ba3baac39d
27.419355
83
0.620885
4.059908
false
false
false
false
XeresRazor/SMGOLFramework
Sources/XMLParser.swift
2
5538
// // XMLParser.swift // SMGOLFramework // // Created by David Green on 2/22/16. // Copyright © 2016 David Green. All rights reserved. // import Foundation public class Parser { private enum State { case Text case Tag case AttributeName case AttributeValue case Comment } private var stream: Stream private var node: Node private var text = "" private var attributeName = "" private var attributeValue = "" private var attributes = [AttributeType]() private var state: State = .Text private var isTagEnd = false private var tagSpace = false private init(stream: Stream, root: Node) { self.stream = stream self.node = root } private func parse() -> Bool { var value: Character do { value = Character(UnicodeScalar(try stream.read8())) } catch { return false } while !stream.isEOF() { var ret = false switch state { case .Text: ret = processCharText(value) case .Tag: ret = processCharTag(value) case .AttributeName: ret = processCharAttributeName(value) case .AttributeValue: ret = processCharAttributeValue(value) case .Comment: ret = processCharComment(value) } if ret == false { return false } do { value = Character(UnicodeScalar(try stream.read8())) } catch { return false } } return true } private func processCharText(char: Character) -> Bool { if char == "<" { // Tag is starting if text.characters.count != 0 { node.insertNode(Node(text: UnescapeText(text), isTag: false)) text = "" } state = .Tag isTagEnd = false tagSpace = false return true } text.append(char) return true } private func processCharTag(char: Character) -> Bool { if char == "!" && text.characters.count == 0 { state = .Comment return true } if char == "<" { // ??? return false } if char == "/" { // This is an end tag isTagEnd = true return true } if char == " " || char == "\t" || char == "\r" || char == "\n" { // Attributes follow state = .AttributeName attributeName = "" return true } if char == ">" { if text[text.startIndex] != "?" { // See if the tag name matches the current nodes name let hasSameName = text == node.text if isTagEnd && hasSameName { // Walk up the tree node = node.parent! } else { // Create a new node let child = Node(text: text, isTag: true) node.insertNode(child) // Copy attributes while attributes.count != 0 { child.insertAttribute(attributes.last!) attributes.removeLast() } // Go down if it's not a singleton if !isTagEnd { node = child } } } text = "" state = .Text return true } text.append(char) return true } private func processCharAttributeName(char: Character) -> Bool { if char == "=" { return true } if char == " " || char == "\t" || char == "\r" || char == "\n" { if attributeName.characters.count == 0 { return true } return false } if char == ">" || char == "/" { state = .Tag return processCharTag(char) } if char == "\"" { state = .AttributeValue attributeValue = "" return true } attributeName.append(char) return true } private func processCharAttributeValue(char: Character) -> Bool { if char == "\"" { attributes.append((attributeName, UnescapeText(attributeValue))) state = .AttributeName attributeName = "" return true } attributeValue.append(char) return true } private func processCharComment(char: Character) -> Bool { if char == ">" { if text[text.endIndex.advancedBy(-2) ..< text.endIndex] == "--" { // Comment end text = "" state = .Text return true } } text.append(char) return true } } public func ParseDocument(stream: Stream) -> Node? { let root = Node() let parser = Parser(stream: stream, root: root) let ret = parser.parse() if !ret { return nil } return root }
mit
08cd258fdfd32b2dce6516862cedeeec
25.366667
77
0.439769
5.375728
false
false
false
false
firebase/friendlypix-ios
FriendlyPix/FPUser.swift
1
1979
// // Copyright (c) 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Firebase class FPUser { var uid: String var fullname: String var profilePictureURL: URL? init(snapshot: DataSnapshot) { self.uid = snapshot.key let value = snapshot.value as! [String: Any] self.fullname = value["full_name"] as? String ?? "" guard let profile_picture = value["profile_picture"] as? String, let profilePictureURL = URL(string: profile_picture) else { return } self.profilePictureURL = profilePictureURL } init(dictionary: [String: String]) { self.uid = dictionary["uid"]! self.fullname = dictionary["full_name"] ?? "" guard let profile_picture = dictionary["profile_picture"], let profilePictureURL = URL(string: profile_picture) else { return } self.profilePictureURL = profilePictureURL } private init(user: User) { self.uid = user.uid self.fullname = user.displayName ?? "" self.profilePictureURL = user.photoURL } static func currentUser() -> FPUser { return FPUser(user: Auth.auth().currentUser!) } func author() -> [String: String] { return ["uid": uid, "full_name": fullname, "profile_picture": profilePictureURL?.absoluteString ?? ""] } } extension FPUser: Equatable { static func ==(lhs: FPUser, rhs: FPUser) -> Bool { return lhs.uid == rhs.uid } static func ==(lhs: FPUser, rhs: User) -> Bool { return lhs.uid == rhs.uid } }
apache-2.0
bd929c10da39e8124b2b26f148adec75
30.412698
106
0.681152
3.99798
false
false
false
false
BobElDevil/ScriptWorker
ScriptWorker/trap.swift
1
728
// Based on this gist https://gist.github.com/sharplet/d640eea5b6c99605ac79 import Darwin enum Signal: Int32 { case HUP = 1 case INT = 2 case QUIT = 3 case ABRT = 6 case KILL = 9 case ALRM = 14 case TERM = 15 } func trap(signal: Signal, action: @convention(c) (Int32) -> ()) { // From Swift, sigaction.init() collides with the Darwin.sigaction() function. // This local typealias allows us to disambiguate them. typealias SignalAction = sigaction var signalAction = SignalAction(__sigaction_u: unsafeBitCast(action, to: __sigaction_u.self), sa_mask: 0, sa_flags: 0) _ = withUnsafePointer(to: &signalAction) { actionPointer in sigaction(signal.rawValue, actionPointer, nil) } }
mit
08b4f8d2d58184e10162cbd952fa1d6f
28.12
120
0.68544
3.309091
false
false
false
false
devincoughlin/swift
test/Parse/enum_element_pattern_swift4.swift
1
2653
// RUN: %target-typecheck-verify-swift -swift-version 4 // https://bugs.swift.org/browse/SR-3452 // See test/Compatibility/enum_element_pattern.swift for Swift3 behavior. // As for FIXME cases: see https://bugs.swift.org/browse/SR-3466 enum E { case A, B, C, D static func testE(e: E) { switch e { case A<UndefinedTy>(): // expected-error {{cannot specialize a non-generic definition}} // expected-note@-1 {{while parsing this '<' as a type parameter bracket}} break case B<Int>(): // expected-error {{cannot specialize a non-generic definition}} expected-note {{while parsing this '<' as a type parameter bracket}} break default: break; } } } func testE(e: E) { switch e { case E.A<UndefinedTy>(): // expected-error {{cannot specialize a non-generic definition}} // expected-note@-1 {{while parsing this '<' as a type parameter bracket}} break case E.B<Int>(): // expected-error {{cannot specialize a non-generic definition}} expected-note {{while parsing this '<' as a type parameter bracket}} break case .C(): // expected-error {{pattern with associated values does not match enum case 'C'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{10-12=}} break case .D(let payload): // expected-error{{pattern with associated values does not match enum case 'D'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{10-23=}} let _: () = payload break default: break } guard case .C() = e, // expected-error {{pattern with associated values does not match enum case 'C'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{12-14=}} case .D(let payload) = e // expected-error {{pattern with associated values does not match enum case 'D'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{12-25=}} // expected-error@-2 {{variable 'payload' is not bound by any pattern}} else { return } } extension E : Error {} func canThrow() throws { throw E.A } do { try canThrow() } catch E.A() { // expected-error {{pattern with associated values does not match enum case 'A'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{12-14=}} // .. } catch E.B(let payload) { // expected-error {{pattern with associated values does not match enum case 'B'}} // expected-note@-1 {{remove associated values to make the pattern match}} {{12-25=}} let _: () = payload }
apache-2.0
edc233258918edd18057aa061b5caedd
41.111111
152
0.630984
4.050382
false
false
false
false
yanagiba/swift-transform
Sources/Transform/Driver.swift
1
1869
/* Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import Source import Parser import Diagnostic import Tooling open class Driver { private var _generator: Generator public init(generator: Generator = Generator()) { _generator = generator } func udpateGenerator(_ generator: Generator) { _generator = generator } @discardableResult public func transform( sourceFile: SourceFile, outputHandle: FileHandle = .standardOutput ) -> Int32 { let diagnosticConsumer = SilentDiagnosticConsumer() let tooling = ToolAction() let result = tooling.run( sourceFiles: [sourceFile], diagnosticConsumer: diagnosticConsumer, options: [.assignLexicalParent]) guard result.exitCode == ToolActionResult.success, let astUnit = result.astUnitCollection.first else { print("Failed in parsing file \(sourceFile.identifier)") // Ignore the errors for now return -1 } let transformed = _generator.generate(astUnit.translationUnit) guard let strData = "\(transformed)\n".data(using: .utf8) else { return -2 } outputHandle.write(strData) return 0 } } private struct SilentDiagnosticConsumer : DiagnosticConsumer { func consume(diagnostics: [Diagnostic]) {} }
apache-2.0
918c15f266f888317c249d6774b80c8b
26.895522
76
0.719636
4.731646
false
false
false
false
svachmic/ios-url-remote
URLRemote/Classes/Controllers/ActionViewCell.swift
1
2172
// // ActionViewCell.swift // URLRemote // // Created by Michal Švácha on 14/12/16. // Copyright © 2016 Svacha, Michal. All rights reserved. // import UIKit import Material /// View for a single action represented by a collection view cell. Drawn as a round button with an icon representing the activity (picked by the user). class ActionViewCell: UICollectionViewCell { var button: RaisedButton? /// Sets up the view by adding the button if it's not presented already. func setUpView() { if button == nil { button = RaisedButton(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height)) button?.backgroundColor = UIColor.gray button?.layer.cornerRadius = self.frame.width / 2.0 self.addSubview(button!) } } /// Binds the button to the specific action. /// - Discussion: This approach works but could be improved. /// - Reason: Every time the button is tapped a new signal object is created. /// /// - Parameter entry: Model object that represents the action. func bind(with entry: Entry) { var color = UIColor.gray if let hex = entry.color { color = UIColor(named: hex) } button?.backgroundColor = color if let imageName = entry.icon, let image = UIImage(named: imageName) { button?.image = image.withRenderingMode(.alwaysTemplate) button?.imageView?.tintColor = .white } button?.pulseColor = .white if let url = entry.url { let action = EntryAction().signalForAction( url: url, validator: ValidatorFactory.validator(for: entry), requiresAuthentication: entry.requiresAuthentication, user: entry.user, password: entry.password) button?.reactive.tap.bind(to: self) { me, _ in me.button?.reactive.action .bind(signal: action.take(first: 1)) .dispose(in: me.reactive.bag) }.dispose(in: reactive.bag) } } }
apache-2.0
d6f1f51d43738937470da69b43023c3a
35.15
152
0.592439
4.605096
false
false
false
false
catloafsoft/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Parametric EQ/AKParametricEQ.swift
1
5057
// // AKParametricEQ.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// AudioKit version of Apple's ParametricEQ Audio Unit /// /// - parameter input: Input node to process /// - parameter centerFrequency: Center Freq (Hz) ranges from 20 to 22050 (Default: 2000) /// - parameter q: Q (Hz) ranges from 0.1 to 20 (Default: 1.0) /// - parameter gain: Gain (dB) ranges from -20 to 20 (Default: 0) /// public class AKParametricEQ: AKNode, AKToggleable { private let cd = AudioComponentDescription( componentType: kAudioUnitType_Effect, componentSubType: kAudioUnitSubType_ParametricEQ, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0) internal var internalEffect = AVAudioUnitEffect() internal var internalAU = AudioUnit() private var mixer: AKMixer /// Center Freq (Hz) ranges from 20 to 22050 (Default: 2000) public var centerFrequency: Double = 2000 { didSet { if centerFrequency < 20 { centerFrequency = 20 } if centerFrequency > 22050 { centerFrequency = 22050 } AudioUnitSetParameter( internalAU, kParametricEQParam_CenterFreq, kAudioUnitScope_Global, 0, Float(centerFrequency), 0) } } /// Q (Hz) ranges from 0.1 to 20 (Default: 1.0) public var q: Double = 1.0 { didSet { if q < 0.1 { q = 0.1 } if q > 20 { q = 20 } AudioUnitSetParameter( internalAU, kParametricEQParam_Q, kAudioUnitScope_Global, 0, Float(q), 0) } } /// Gain (dB) ranges from -20 to 20 (Default: 0) public var gain: Double = 0 { didSet { if gain < -20 { gain = -20 } if gain > 20 { gain = 20 } AudioUnitSetParameter( internalAU, kParametricEQParam_Gain, kAudioUnitScope_Global, 0, Float(gain), 0) } } /// Dry/Wet Mix (Default 100) public var dryWetMix: Double = 100 { didSet { if dryWetMix < 0 { dryWetMix = 0 } if dryWetMix > 100 { dryWetMix = 100 } inputGain?.volume = 1 - dryWetMix / 100 effectGain?.volume = dryWetMix / 100 } } private var lastKnownMix: Double = 100 private var inputGain: AKMixer? private var effectGain: AKMixer? /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted = true /// Initialize the parametric eq node /// /// - parameter input: Input node to process /// - parameter centerFrequency: Center Frequency (Hz) ranges from 20 to 22050 (Default: 2000) /// - parameter q: Q (Hz) ranges from 0.1 to 20 (Default: 1.0) /// - parameter gain: Gain (dB) ranges from -20 to 20 (Default: 0) /// public init( _ input: AKNode, centerFrequency: Double = 2000, q: Double = 1.0, gain: Double = 0) { self.centerFrequency = centerFrequency self.q = q self.gain = gain inputGain = AKMixer(input) inputGain!.volume = 0 mixer = AKMixer(inputGain!) effectGain = AKMixer(input) effectGain!.volume = 1 internalEffect = AVAudioUnitEffect(audioComponentDescription: cd) super.init() AudioKit.engine.attachNode(internalEffect) internalAU = internalEffect.audioUnit AudioKit.engine.connect((effectGain?.avAudioNode)!, to: internalEffect, format: AudioKit.format) AudioKit.engine.connect(internalEffect, to: mixer.avAudioNode, format: AudioKit.format) avAudioNode = mixer.avAudioNode AudioUnitSetParameter(internalAU, kParametricEQParam_CenterFreq, kAudioUnitScope_Global, 0, Float(centerFrequency), 0) AudioUnitSetParameter(internalAU, kParametricEQParam_Q, kAudioUnitScope_Global, 0, Float(q), 0) AudioUnitSetParameter(internalAU, kParametricEQParam_Gain, kAudioUnitScope_Global, 0, Float(gain), 0) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { if isStopped { dryWetMix = lastKnownMix isStarted = true } } /// Function to stop or bypass the node, both are equivalent public func stop() { if isPlaying { lastKnownMix = dryWetMix dryWetMix = 0 isStarted = false } } }
mit
d01628745cb3a32b7c0a60b8055643cb
30.60625
130
0.562389
5.108081
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/CoreStore/CoreStore/Migrating/MigrationChain.swift
2
8356
// // MigrationChain.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - MigrationChain /** A `MigrationChain` indicates the sequence of model versions to be used as the order for progressive migrations. This is typically passed to the `DataStack` initializer and will be applied to all stores added to the `DataStack` with `addSQLiteStore(...)` and its variants. Initializing with empty values (either `nil`, `[]`, or `[:]`) instructs the `DataStack` to use the .xcdatamodel's current version as the final version, and to disable progressive migrations: ``` let dataStack = DataStack(migrationChain: nil) ``` This means that the mapping model will be computed from the store's version straight to the `DataStack`'s model version. To support progressive migrations, specify the linear order of versions: ``` let dataStack = DataStack(migrationChain: ["MyAppModel", "MyAppModelV2", "MyAppModelV3", "MyAppModelV4"]) ``` or for more complex migration paths, a version tree that maps the key-values to the source-destination versions: ``` let dataStack = DataStack(migrationChain: [ "MyAppModel": "MyAppModelV3", "MyAppModelV2": "MyAppModelV4", "MyAppModelV3": "MyAppModelV4" ]) ``` This allows for different migration paths depending on the starting version. The example above resolves to the following paths: - MyAppModel-MyAppModelV3-MyAppModelV4 - MyAppModelV2-MyAppModelV4 - MyAppModelV3-MyAppModelV4 The `MigrationChain` is validated when passed to the `DataStack` and unless it is empty, will raise an assertion if any of the following conditions are met: - a version appears twice in an array - a version appears twice as a key in a dictionary literal - a loop is found in any of the paths */ public struct MigrationChain: NilLiteralConvertible, StringLiteralConvertible, DictionaryLiteralConvertible, ArrayLiteralConvertible { // MARK: NilLiteralConvertible public init(nilLiteral: ()) { self.versionTree = [:] self.rootVersions = [] self.leafVersions = [] self.valid = true } // MARK: StringLiteralConvertible public init(stringLiteral value: String) { self.versionTree = [:] self.rootVersions = [value] self.leafVersions = [value] self.valid = true } // MARK: ExtendedGraphemeClusterLiteralConvertible public init(extendedGraphemeClusterLiteral value: String) { self.versionTree = [:] self.rootVersions = [value] self.leafVersions = [value] self.valid = true } // MARK: UnicodeScalarLiteralConvertible public init(unicodeScalarLiteral value: String) { self.versionTree = [:] self.rootVersions = [value] self.leafVersions = [value] self.valid = true } // MARK: DictionaryLiteralConvertible public init(dictionaryLiteral elements: (String, String)...) { var valid = true var versionTree = [String: String]() elements.forEach { (sourceVersion, destinationVersion) in guard let _ = versionTree.updateValue(destinationVersion, forKey: sourceVersion) else { return } CoreStore.assert(false, "\(typeName(MigrationChain))'s migration chain could not be created due to ambiguous version paths.") valid = false } let leafVersions = Set( elements.filter { (tuple: (String, String)) -> Bool in return versionTree[tuple.1] == nil }.map { $1 } ) let isVersionAmbiguous = { (start: String) -> Bool in var checklist: Set<String> = [start] var version = start while let nextVersion = versionTree[version] where nextVersion != version { if checklist.contains(nextVersion) { CoreStore.assert(false, "\(typeName(MigrationChain))'s migration chain could not be created due to looping version paths.") return true } checklist.insert(nextVersion) version = nextVersion } return false } self.versionTree = versionTree self.rootVersions = Set(versionTree.keys).subtract(versionTree.values) self.leafVersions = leafVersions self.valid = valid && Set(versionTree.keys).union(versionTree.values).filter { isVersionAmbiguous($0) }.count <= 0 } // MARK: ArrayLiteralConvertible public init(arrayLiteral elements: String...) { CoreStore.assert(Set(elements).count == elements.count, "\(typeName(MigrationChain))'s migration chain could not be created due to duplicate version strings.") var lastVersion: String? var versionTree = [String: String]() var valid = true for version in elements { if let lastVersion = lastVersion, let _ = versionTree.updateValue(version, forKey: lastVersion) { valid = false } lastVersion = version } self.versionTree = versionTree self.rootVersions = Set([elements.first].flatMap { $0 == nil ? [] : [$0!] }) self.leafVersions = Set([elements.last].flatMap { $0 == nil ? [] : [$0!] }) self.valid = valid } // MARK: Internal internal let rootVersions: Set<String> internal let leafVersions: Set<String> internal let valid: Bool internal var empty: Bool { return self.versionTree.count <= 0 } internal func contains(version: String) -> Bool { return self.rootVersions.contains(version) || self.leafVersions.contains(version) || self.versionTree[version] != nil } internal func nextVersionFrom(version: String) -> String? { guard let nextVersion = self.versionTree[version] where nextVersion != version else { return nil } return nextVersion } // MARK: Private private let versionTree: [String: String] } // MARK: - MigrationChain: CustomDebugStringConvertible extension MigrationChain: CustomDebugStringConvertible { public var debugDescription: String { guard self.valid else { return "<invalid migration chain>" } var paths = [String]() for var version in self.rootVersions { var steps = [version] while let nextVersion = self.nextVersionFrom(version) { steps.append(nextVersion) version = nextVersion } paths.append(steps.joinWithSeparator(" → ")) } return "[" + paths.joinWithSeparator("], [") + "]" } }
apache-2.0
184fa106bf82ac925525e84be9948d68
33.093878
272
0.617024
5.286709
false
false
false
false
HabitRPG/habitrpg-ios
Habitica Models/Habitica Models/User/SubscriptionPlanProtocol.swift
1
1233
// // SubscriptionPlanProtocol.swift // Habitica Models // // Created by Phillip Thelen on 23.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation @objc public protocol SubscriptionPlanProtocol { var quantity: Int { get set } var gemsBought: Int { get set } var dateTerminated: Date? { get set } var dateUpdated: Date? { get set } var dateCreated: Date? { get set } var planId: String? { get set } var customerId: String? { get set } var paymentMethod: String? { get set } var consecutive: SubscriptionConsecutiveProtocol? { get set } var mysteryItems: [String] { get set } } public extension SubscriptionPlanProtocol { var isActive: Bool { if let dateTerminated = dateTerminated { if dateTerminated < Date() { return false } } return customerId != nil } var isGifted: Bool { return customerId == "Gift" } var isGroupPlanSub: Bool { return customerId == "group-plan" } var gemCapTotal: Int { return 25 + (consecutive?.gemCapExtra ?? 0) } var gemsRemaining: Int { return gemCapTotal - gemsBought } }
gpl-3.0
b9322b1ec100e81ebe5695c65ff70ee6
23.64
65
0.611201
4.176271
false
false
false
false
hughbe/swift
test/SILGen/objc_dealloc.swift
2
4409
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen | %FileCheck %s // REQUIRES: objc_interop import gizmo class X { } func onDestruct() { } @requires_stored_property_inits class SwiftGizmo : Gizmo { var x = X() // CHECK-LABEL: sil hidden [transparent] @_T012objc_dealloc10SwiftGizmoC1xAA1XCvfi : $@convention(thin) () -> @owned X // CHECK: [[FN:%.*]] = function_ref @_T012objc_dealloc1XCACycfC : $@convention(method) (@thick X.Type) -> @owned X // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick X.Type // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thick X.Type) -> @owned X // CHECK-NEXT: return [[RESULT]] : $X // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $SwiftGizmo): override init() { // CHECK: [[SELF_UNINIT:%[0-9]+]] = mark_uninitialized [derivedselfonly] // CHECK-NOT: ref_element_addr // CHECK: upcast // CHECK-NEXT: super_method // CHECK: return super.init() } // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> () deinit { // CHECK: bb0([[SELF:%[0-9]+]] : $SwiftGizmo): // Call onDestruct() // CHECK: [[ONDESTRUCT_REF:%[0-9]+]] = function_ref @_T012objc_dealloc10onDestructyyF : $@convention(thin) () -> () // CHECK: [[ONDESTRUCT_RESULT:%[0-9]+]] = apply [[ONDESTRUCT_REF]]() : $@convention(thin) () -> () onDestruct() // Note: don't destroy instance variables // CHECK-NOT: ref_element_addr // Call super -dealloc. // CHECK: [[SUPER_DEALLOC:%[0-9]+]] = super_method [[SELF]] : $SwiftGizmo, #Gizmo.deinit!deallocator.foreign : (Gizmo) -> () -> (), $@convention(objc_method) (Gizmo) -> () // CHECK: [[SUPER:%[0-9]+]] = upcast [[SELF]] : $SwiftGizmo to $Gizmo // CHECK: [[SUPER_DEALLOC_RESULT:%[0-9]+]] = apply [[SUPER_DEALLOC]]([[SUPER]]) : $@convention(objc_method) (Gizmo) -> () // CHECK: [[RESULT:%[0-9]+]] = tuple () // CHECK: return [[RESULT]] : $() } // Objective-C deallocation deinit thunk (i.e., -dealloc). // CHECK-LABEL: sil hidden [thunk] @_T012objc_dealloc10SwiftGizmoCfDTo : $@convention(objc_method) (SwiftGizmo) -> () // CHECK: bb0([[SELF:%[0-9]+]] : $SwiftGizmo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[GIZMO_DTOR:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoCfD : $@convention(method) (@owned SwiftGizmo) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[GIZMO_DTOR]]([[SELF_COPY]]) : $@convention(method) (@owned SwiftGizmo) -> () // CHECK: return [[RESULT]] : $() // Objective-C IVar initializer (i.e., -.cxx_construct) // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfeTo : $@convention(objc_method) (@owned SwiftGizmo) -> @owned SwiftGizmo // CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $SwiftGizmo): // CHECK-NEXT: debug_value [[SELF_PARAM]] : $SwiftGizmo, let, name "self" // CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_PARAM]] : $SwiftGizmo // CHECK: [[XINIT:%[0-9]+]] = function_ref @_T012objc_dealloc10SwiftGizmoC1xAA1XCvfi // CHECK-NEXT: [[XOBJ:%[0-9]+]] = apply [[XINIT]]() : $@convention(thin) () -> @owned X // CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[BORROWED_SELF]] : $SwiftGizmo, #SwiftGizmo.x // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[X]] : $*X // CHECK-NEXT: assign [[XOBJ]] to [[WRITE]] : $*X // CHECK-NEXT: end_access [[WRITE]] : $*X // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK-NEXT: return [[SELF]] : $SwiftGizmo // Objective-C IVar destroyer (i.e., -.cxx_destruct) // CHECK-LABEL: sil hidden @_T012objc_dealloc10SwiftGizmoCfETo : $@convention(objc_method) (SwiftGizmo) -> () // CHECK: bb0([[SELF:%[0-9]+]] : $SwiftGizmo): // CHECK-NEXT: debug_value [[SELF]] : $SwiftGizmo, let, name "self" // CHECK-NEXT: [[X:%[0-9]+]] = ref_element_addr [[SELF]] : $SwiftGizmo, #SwiftGizmo.x // CHECK-NEXT: destroy_addr [[X]] : $*X // CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() } // CHECK-NOT: sil hidden [thunk] @_T0So11SwiftGizmo2CfETo : $@convention(objc_method) (SwiftGizmo2) -> () class SwiftGizmo2 : Gizmo { }
apache-2.0
bb203bd46b47f67cd091f7d89a1b93b6
50.267442
177
0.599909
3.312547
false
false
false
false
palle-k/SocketKit
Sources/OutputStream.swift
2
12351
// // OutputStream.swift // SocketKit // // Created by Palle Klewitz on 11.04.16. // Copyright © 2016 Palle Klewitz. // // 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 CoreFoundation import Darwin import Foundation /** Output stream for writing to an underlying target. **Implementation notes:** Only the function `write(data: UnsafePointer<Void>, lengthInBytes byteCount: Int) throws` should be implemented. Other `write`/`writeln` functions should not be implemented as they are already implemented as an extension which will call the `write(data: UnsafePointer<Void>, lengthInBytes byteCount: Int) throws` function. */ public protocol OutputStream { /** True, if the stream is open and data can be written. False, if the stream is closed and data cannot be written. Any calls of the write-function will fail and an IOError will be thrown. If the state of the stream changes, the delegate is notified by a call of the `didClose`-Method. */ var open:Bool { get } /** Writes the given data into the underlying ressource. The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter data: Data which should be written. - throws: An IOError indicating that the operation failed. */ func write(_ data: Data) throws /** Writes the given string encoded by the given encoding into the underlying ressource. The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter string: String which should be written - parameter encoding: Encoding to be used to convert the string to bytes. By default the string will be encoded using UTF-8 encoding. - throws: An IOError indicating that the operation failed. */ func write(_ string: String, encoding: String.Encoding) throws /** Writes the data at the given pointer into the underlying target. The byteCount specifies that The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter data: Pointer to the data to be written - parameter byteCount: Number of bytes to be written - throws: An IOError indicating that the operation failed. */ func write(_ data: UnsafeRawPointer, lengthInBytes byteCount: Int) throws /** Writes the given StreamWritable-object into the underlying target. The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter streamWritable: The object to be written. - throws: An IOError indicating that the operation failed. */ func write(_ streamWritable: StreamWritable) throws /** Writes the given string followed by a newline encoded by the given encoding into the underlying ressource. The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter string: String which should be written. If no string is specified, only a newline will be written. - parameter encoding: Encoding to be used to convert the string to bytes. By default the string will be encoded using UTF-8 encoding. - throws: An IOError indicating that the operation failed. */ func writeln(_ string: String, encoding: String.Encoding) throws /** Closes the stream and releases any associated ressources. Subsequent calls to the write-function should fail with an IOError. If the stream writes into a socket, the socket should be notified of this operation so it can be closed automatically if both streams are closed. */ func close() } /** Extension of the OutputStream protocol for the default implementation of write-function overloads. */ public extension OutputStream { /** Writes the given data into the underlying ressource. The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter data: Data which should be written. - throws: An IOError indicating that the operation failed. */ public func write(_ data: Data) throws { try write((data as NSData).bytes, lengthInBytes: data.count) } /** Writes the data at the given pointer into the underlying target. The byteCount specifies that The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter data: Pointer to the data to be written - parameter byteCount: Number of bytes to be written - throws: An IOError indicating that the operation failed. */ public func write(_ string: String, encoding: String.Encoding = String.Encoding.utf8) throws { guard let data = string.data(using: encoding) else { throw DataError.stringConversion } try write(data) } /** Writes the given string followed by a newline encoded by the given encoding into the underlying ressource. The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter string: String which should be written. If no string is specified, only a newline will be written. - parameter encoding: Encoding to be used to convert the string to bytes. By default the string will be encoded using UTF-8 encoding. - throws: An IOError indicating that the operation failed. */ public func writeln(_ string: String = "", encoding: String.Encoding = String.Encoding.utf8) throws { guard let data = "\(string)\r\n".data(using: encoding) else { throw DataError.stringConversion } try write(data) } /** Writes the given StreamWritable-object into the underlying target. The error may be .WouldBlock or .Again, which indicates that the read operation failed because no data is available and non-blocking I/O is used. In this case, the write operation has to be repeated. - parameter streamWritable: The object to be written. - throws: An IOError indicating that the operation failed. */ public func write(_ streamWritable: StreamWritable) throws { try streamWritable.write(to: self) } } /** Protocol for stream-serialization of objects. A type implementing this protocol can write itself into an OutputStream. If an object should also be stream-deserializable, it must implement the StreamReadable-protocol. */ public protocol StreamWritable { /** Writes the object into the given stream. If any write operation fails, this method may throw an IOError. - parameter outputStream: Stream to write this object to - throws: An IOError indicating that the operation failed. */ func write(to outputStream: OutputStream) throws } /** Implementation of the OutputStream protocol for writing into a POSIX-socket. */ internal class SocketOutputStreamImpl : OutputStream { /** The posix socket handle for network writing. */ fileprivate let handle: Int32 /** Socket, to which this stream writes data. If the stream is closed, the socket will be notified of this and close itself, if both streams are closed. */ fileprivate weak var socket: Socket? /** Specifies, if this stream is open and data can be written to it. If the stream is closed and a write operation is initiated, an IOError will be thrown. */ internal fileprivate(set) var open = false /** Initializes the stream with the socket to write to and the POSIX-socket handle for write operations. - parameter socket: The socket to which this stream writes. - parameter handle: The POSIX-socket handle for write operations. */ internal init(socket: Socket, handle: Int32) { self.socket = socket self.handle = handle self.open = true } /** Writes the given data of the specified length into the underlying POSIX-socket. If the operation fails, an IOError is thrown. If an .Interrupted error is thrown, the operation has to be repeated. - parameter data: Pointer to the data to be written. - parameter byteCount: Number of bytes to be written. - throws: An IOError indicating that the write operation failed. */ internal func write(_ data: UnsafeRawPointer, lengthInBytes byteCount: Int) throws { assert(byteCount >= 0, "Byte count must be greater than or equal to zero.") DEBUG_HEXDUMP ?-> print("Write:\n\(hex(data, length: byteCount))") var advance = 0 repeat { let maxBytes = byteCount - advance DEBUG ?-> print("Writing into socket... (left: \(maxBytes), written: \(advance))") let written = Darwin.write(handle, data.advanced(by: advance), maxBytes) DEBUG ?-> print("\(written) bytes written.") if written < 0 && !(errno == EAGAIN || errno == EINTR) { DEBUG ?-> print("An error occurred while writing. Check thrown IOError.") DEBUG ?-> print(String(cString: strerror(errno))) let error = IOError.FromCurrentErrno() if error != .wouldBlock { socket?.close() } throw error } else { advance += max(written, 0) } } while advance < byteCount } /** Closes the stream manually and shuts down the socket so no more write calls are possible. Subsequent calls to the write-function function will fail. */ internal func close() { guard open else { return } open = false shutdown(handle, SHUT_WR) socket?.checkStreams() } /** When deinitialized, the stream will be closed. */ deinit { close() } } internal class SystemOutputStream : NSObject, OutputStream, StreamDelegate { fileprivate(set) var open: Bool fileprivate let underlyingStream: Foundation.OutputStream internal init(underlyingStream: Foundation.OutputStream) { self.underlyingStream = underlyingStream open = true super.init() self.underlyingStream.delegate = self self.underlyingStream.open() } func write(_ data: UnsafeRawPointer, lengthInBytes byteCount: Int) throws { guard open else { throw underlyingStream.streamError ?? IOError.notConnected } var offset = 0; repeat { let written = underlyingStream.write(data.advanced(by: offset).assumingMemoryBound(to: UInt8.self), maxLength: byteCount - offset) if written < 0 { throw underlyingStream.streamError ?? IOError.unknown } offset += written } while offset < byteCount } func close() { underlyingStream.close() } @objc func stream(_ aStream: Stream, handle eventCode: Stream.Event) { switch eventCode { case Stream.Event.endEncountered, Stream.Event.errorOccurred: open = false break default: break } } }
mit
40ab22d4840d268f1eaeaaaa1c88d794
22.980583
133
0.727368
4.017567
false
false
false
false
averagedude2992/tapper2App
Tapper2/Tapper2/ViewController.swift
1
2478
// // ViewController.swift // Tapper2 // // Created by Briano Santos on 8/30/16. // Copyright © 2016 FairSkiesTechnologies. All rights reserved. // import UIKit class ViewController: UIViewController { //Properties var maxTaps = 0 var currentTaps = 0 //Outlets @IBOutlet weak var tapperLogo: UIImageView! @IBOutlet weak var howManyTxtField: UITextField! @IBOutlet weak var playBtn: UIButton! @IBOutlet weak var coinBtn: UIButton! @IBOutlet weak var tapsLbl: UILabel! @IBAction func onPlayBtnPressed(sender: AnyObject) { if howManyTxtField.text != nil && howManyTxtField.text != "" { tapperLogo.hidden = true howManyTxtField.hidden = true playBtn.hidden = true coinBtn.hidden = false tapsLbl.hidden = false maxTaps = Int(howManyTxtField.text!)! currentTaps = 0 updateTapsLbl() } } @IBAction func onCoinBtnPressed(sender: AnyObject) { currentTaps += 1 updateTapsLbl() isGameOver() } func updateTapsLbl() { tapsLbl.text = "\(currentTaps) Tapz" } func isGameOver() { if currentTaps >= maxTaps { restartGame() } } func restartGame() { tapperLogo.hidden = false howManyTxtField.hidden = false playBtn.hidden = false coinBtn.hidden = true tapsLbl.hidden = true maxTaps = 0 howManyTxtField.text = "" } // BEGIN stachExchange code (cut/paste) to make the keyboard dissappear when the screen is tapped https://stackoverflow.com/questions/24126678/close-ios-keyboard-by-touching-anywhere-using-swift override func viewDidLoad() { super.viewDidLoad() //Looks for single or multiple taps. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } //Calls this function when the tap is recognized. func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) // END stachExchange code } }
mit
0d4be1d9c50c89bc286f37aced6465b8
23.058252
198
0.577311
5.160417
false
false
false
false
theabovo/Extend
Sources/Helpers/EasyTimer.swift
1
1157
// // Copyright (c) 2016-present, Menly ApS // All rights reserved. // // This source code is licensed under the Apache License 2.0 found in the // LICENSE file in the root directory of this source tree. // import Foundation /// Easily mesaure blocks of code time. Used for quick overview. /// For real performance tuning, use `os_signpost` and the profiler. public enum EasyTimer { @discardableResult /// Quickly measure the time of a block of code. /// /// - Parameters: /// - funcName: The func where this function is called from, filled out automatically. /// - line: The line where this function is called from, filled out automatically. /// - file: The file where this function is called from, filled out automatically. /// - block: The block of code to run. /// - Returns: The result A. static func measure<A>(funcName: String = #function, line: Int = #line, file: String = #file, _ block: () -> A) -> A { let startTime = CACurrentMediaTime() let result = block() let timeElapsed = CACurrentMediaTime() - startTime print("Easy timer measured: \(file):\(funcName):\(line) - result: \(timeElapsed)") return result } }
apache-2.0
e27255c9fbbdb8ddea1c5292fb488c95
35.15625
119
0.691443
3.805921
false
false
false
false
anthonypuppo/GDAXSwift
GDAXSwift/Classes/GDAXProductOrderBook.swift
1
2075
// // GDAXProductOrderBook.swift // GDAXSwift // // Created by Anthony on 6/4/17. // Copyright © 2017 Anthony Puppo. All rights reserved. // public struct GDAXProductOrderBook: JSONInitializable { public let sequence: Int public let bids: [GDAXBid] public let asks: [GDAXAsk] internal init(json: Any) throws { var jsonData: Data? if let json = json as? Data { jsonData = json } else { jsonData = try JSONSerialization.data(withJSONObject: json, options: []) } guard let json = jsonData?.json else { throw GDAXError.invalidResponseData } guard let sequence = json["sequence"] as? Int else { throw GDAXError.responseParsingFailure("sequence") } guard let bidArray = json["bids"] as? [[Any]] else { throw GDAXError.responseParsingFailure("bids") } guard let askArray = json["asks"] as? [[Any]] else { throw GDAXError.responseParsingFailure("asks") } self.sequence = sequence var bids = [GDAXBid]() var asks = [GDAXAsk]() for bid in bidArray { guard bid.count == 3 else { throw GDAXError.responseParsingFailure("One or more bids did not have an array length of 3") } guard let price = Double(bid[0] as? String ?? "") else { throw GDAXError.responseParsingFailure("price") } guard let size = Double(bid[1] as? String ?? "") else { throw GDAXError.responseParsingFailure("size") } bids.append(GDAXBid(price: price, size: size, numOrders: bid[2] as? Int, orderID: bid[2] as? String)) } for ask in askArray { guard ask.count == 3 else { throw GDAXError.responseParsingFailure("One or more asks did not have an array length of 3") } guard let price = Double(ask[0] as? String ?? "") else { throw GDAXError.responseParsingFailure("price") } guard let size = Double(ask[1] as? String ?? "") else { throw GDAXError.responseParsingFailure("size") } asks.append(GDAXAsk(price: price, size: size, numOrders: ask[2] as? Int, orderID: ask[2] as? String)) } self.bids = bids self.asks = asks } }
mit
c26bcee23d91a94f3038be743e7f654b
24.604938
104
0.65622
3.545299
false
false
false
false
djwbrown/swift
stdlib/private/SwiftPrivatePthreadExtras/SwiftPrivatePthreadExtras.swift
7
4694
//===--- SwiftPrivatePthreadExtras.swift ----------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file contains wrappers for pthread APIs that are less painful to use // than the C APIs. // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) import Glibc #endif /// An abstract base class to encapsulate the context necessary to invoke /// a block from pthread_create. internal class PthreadBlockContext { /// Execute the block, and return an `UnsafeMutablePointer` to memory /// allocated with `UnsafeMutablePointer.alloc` containing the result of the /// block. func run() -> UnsafeMutableRawPointer { fatalError("abstract") } } internal class PthreadBlockContextImpl<Argument, Result>: PthreadBlockContext { let block: (Argument) -> Result let arg: Argument init(block: @escaping (Argument) -> Result, arg: Argument) { self.block = block self.arg = arg super.init() } override func run() -> UnsafeMutableRawPointer { let result = UnsafeMutablePointer<Result>.allocate(capacity: 1) result.initialize(to: block(arg)) return UnsafeMutableRawPointer(result) } } /// Entry point for `pthread_create` that invokes a block context. internal func invokeBlockContext( _ contextAsVoidPointer: UnsafeMutableRawPointer? ) -> UnsafeMutableRawPointer! { // The context is passed in +1; we're responsible for releasing it. let context = Unmanaged<PthreadBlockContext> .fromOpaque(contextAsVoidPointer!) .takeRetainedValue() return context.run() } #if os(Cygwin) || os(FreeBSD) public typealias _stdlib_pthread_attr_t = UnsafePointer<pthread_attr_t?> #else public typealias _stdlib_pthread_attr_t = UnsafePointer<pthread_attr_t> #endif /// Block-based wrapper for `pthread_create`. public func _stdlib_pthread_create_block<Argument, Result>( _ attr: _stdlib_pthread_attr_t?, _ start_routine: @escaping (Argument) -> Result, _ arg: Argument ) -> (CInt, pthread_t?) { let context = PthreadBlockContextImpl(block: start_routine, arg: arg) // We hand ownership off to `invokeBlockContext` through its void context // argument. let contextAsVoidPointer = Unmanaged.passRetained(context).toOpaque() var threadID = _make_pthread_t() let result = pthread_create(&threadID, attr, { invokeBlockContext($0) }, contextAsVoidPointer) if result == 0 { return (result, threadID) } else { return (result, nil) } } #if os(Linux) || os(Android) internal func _make_pthread_t() -> pthread_t { return pthread_t() } #else internal func _make_pthread_t() -> pthread_t? { return nil } #endif /// Block-based wrapper for `pthread_join`. public func _stdlib_pthread_join<Result>( _ thread: pthread_t, _ resultType: Result.Type ) -> (CInt, Result?) { var threadResultRawPtr: UnsafeMutableRawPointer? let result = pthread_join(thread, &threadResultRawPtr) if result == 0 { let threadResultPtr = threadResultRawPtr!.assumingMemoryBound( to: Result.self) let threadResult = threadResultPtr.pointee threadResultPtr.deinitialize() threadResultPtr.deallocate(capacity: 1) return (result, threadResult) } else { return (result, nil) } } public class _stdlib_Barrier { var _pthreadBarrier: _stdlib_pthread_barrier_t var _pthreadBarrierPtr: UnsafeMutablePointer<_stdlib_pthread_barrier_t> { return _getUnsafePointerToStoredProperties(self) .assumingMemoryBound(to: _stdlib_pthread_barrier_t.self) } public init(threadCount: Int) { self._pthreadBarrier = _stdlib_pthread_barrier_t() let ret = _stdlib_pthread_barrier_init( _pthreadBarrierPtr, nil, CUnsignedInt(threadCount)) if ret != 0 { fatalError("_stdlib_pthread_barrier_init() failed") } } deinit { let ret = _stdlib_pthread_barrier_destroy(_pthreadBarrierPtr) if ret != 0 { fatalError("_stdlib_pthread_barrier_destroy() failed") } } public func wait() { let ret = _stdlib_pthread_barrier_wait(_pthreadBarrierPtr) if !(ret == 0 || ret == _stdlib_PTHREAD_BARRIER_SERIAL_THREAD) { fatalError("_stdlib_pthread_barrier_wait() failed") } } }
apache-2.0
c0cdd3e028dec1d09adfbea37983a94d
30.716216
80
0.677035
4.095986
false
false
false
false
RyoAbe/PARTNER
PARTNER/PARTNER WatchKit Extension/InterfaceController.swift
1
1711
// // InterfaceController.swift // PARTNER WatchKit Extension // // Created by RyoAbe on 2015/05/04. // Copyright (c) 2015年 RyoAbe. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet weak var tableView: WKInterfaceTable! override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) tableView.setNumberOfRows(StatusTypes.count, withRowType: "Cell") for i in 0...(StatusTypes.count - 1) { let row = tableView.rowControllerAtIndex(i) as! StatusMenu let type = StatusTypes(rawValue: i)!.statusType row.textLabel.setText(type.name) row.imageView.setImage(UIImage(named: type.iconImageName)) } } override func table(table: WKInterfaceTable, didSelectRowAtIndex rowIndex: Int) { if let row = table.rowControllerAtIndex(rowIndex) as? StatusMenu { let types = StatusTypes(rawValue: rowIndex)! setTitle(LocalizedString.key("SendMessage")) WKInterfaceController.openParentApplication(["StatusType": types.statusType.identifier ]) { replay, error in Logger.debug("replay=\(replay)") if let succeed = replay["succeed"] as? Bool { self.setTitle(LocalizedString.key(succeed ? "SucceededSendMessage" : "FailedSendMessage")) let when = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()){ self.setTitle(nil) } } } } } }
gpl-3.0
6521dbd9eb0ba6d723c15aebe2f3dc6a
36.977778
120
0.61849
4.939306
false
false
false
false
eaplatanios/swift-rl
Sources/ReinforcementLearning/Agents/Agents.swift
1
12630
// Copyright 2019, Emmanouil Antonios Platanios. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. import TensorFlow public typealias StepCallback<E: Environment, State> = (inout E, inout Trajectory<E.Observation, State, E.Action, E.Reward>) -> Void public protocol Agent { associatedtype Environment: ReinforcementLearning.Environment associatedtype State var actionSpace: Environment.ActionSpace { get } var state: State { get set } mutating func action(for step: Step<Observation, Reward>) -> Action /// Updates this agent, effectively performing a single training step. /// /// - Parameter trajectory: Trajectory to use for the update. /// - Returns: Loss function value. @discardableResult mutating func update(using trajectory: Trajectory<Observation, State, Action, Reward>) -> Float @discardableResult mutating func update( using environment: inout Environment, maxSteps: Int, maxEpisodes: Int, callbacks: [StepCallback<Environment, State>] ) throws -> Float } extension Agent where State == Empty { public var state: State { get { Empty() } set {} } } extension Agent { public typealias Observation = Environment.Observation public typealias Action = Environment.Action public typealias Reward = Environment.Reward @inlinable public mutating func run( in environment: inout Environment, maxSteps: Int = Int.max, maxEpisodes: Int = Int.max, callbacks: [StepCallback<Environment, State>] = [] ) throws { var currentStep = environment.currentStep var numSteps = 0 var numEpisodes = 0 while numSteps < maxSteps && numEpisodes < maxEpisodes { let state = self.state let action = self.action(for: currentStep) let nextStep = try environment.step(taking: action) var trajectory = Trajectory( stepKind: nextStep.kind, observation: currentStep.observation, state: state, action: action, reward: nextStep.reward) callbacks.forEach { $0(&environment, &trajectory) } numSteps += Int((1 - Tensor<Int32>(nextStep.kind.isLast())).sum().scalarized()) numEpisodes += Int(Tensor<Int32>(nextStep.kind.isLast()).sum().scalarized()) currentStep = nextStep } } } /// Trajectory generated by having an agent interact with an environment. /// /// Trajectories consist of five main components, each of which can be a nested structure of /// tensors with shapes whose first two dimensions are `[T, B]`, where `T` is the length of the /// trajectory in terms of time steps and `B` is the batch size. The five components are: /// - `stepKind`: Represents the kind of each time step (i.e., "first", "transition", or "last"). /// For example, if the agent takes an action in time step `t` that results in the current /// episode ending, then `stepKind[t]` will be "last" and `stepKind[t + 1]` will be "first". /// - `observation`: Observation that the agent receives from the environment in the beginning /// of each time step. /// - `state`: State of the agent at the beginning of each time step. /// - `action`: Action the agent took in each time step. /// - `reward`: Reward that the agent received from the environment after each action. The reward /// received after taking `action[t]` is `reward[t]`. public struct Trajectory<Observation, State, Action, Reward>: KeyPathIterable { // These need to be mutable because we use `KeyPathIterable.recursivelyAllWritableKeyPaths` to // automatically derive conformance to `Replayable`. public var stepKind: StepKind public var observation: Observation public var state: State public var action: Action public var reward: Reward @inlinable public init( stepKind: StepKind, observation: Observation, state: State, action: Action, reward: Reward ) { self.stepKind = stepKind self.observation = observation self.state = state self.action = action self.reward = reward } } public struct AnyAgent<Environment: ReinforcementLearning.Environment, State>: Agent { public typealias Observation = Environment.Observation public typealias Action = Environment.Action public typealias Reward = Environment.Reward @usableFromInline internal let _actionSpace: () -> Environment.ActionSpace @usableFromInline internal let _getState: () -> State @usableFromInline internal let _setState: (State) -> Void @usableFromInline internal let _action: (Step<Observation, Reward>) -> Action @usableFromInline internal let _updateUsingTrajectory: ( Trajectory<Observation, State, Action, Reward> ) -> Float @usableFromInline internal let _updateUsingEnvironment: ( inout Environment, Int, Int, [StepCallback<Environment, State>] ) throws -> Float public var actionSpace: Environment.ActionSpace { _actionSpace() } public var state: State { get { _getState() } set { _setState(newValue) } } @inlinable public init<A: Agent>(_ agent: A) where A.Environment == Environment, A.State == State { var agent = agent _actionSpace = { () in agent.actionSpace } _getState = { () in agent.state } _setState = { agent.state = $0 } _action = { agent.action(for: $0) } _updateUsingTrajectory = { agent.update(using: $0) } _updateUsingEnvironment = { try agent.update( using: &$0, maxSteps: $1, maxEpisodes: $2, callbacks: $3) } } @inlinable public mutating func action(for step: Step<Observation, Reward>) -> Action { _action(step) } @inlinable @discardableResult public mutating func update( using trajectory: Trajectory<Observation, State, Action, Reward> ) -> Float { _updateUsingTrajectory(trajectory) } @inlinable @discardableResult public mutating func update( using environment: inout Environment, maxSteps: Int = Int.max, maxEpisodes: Int = Int.max, callbacks: [StepCallback<Environment, State>] = [] ) throws -> Float { try _updateUsingEnvironment(&environment, maxSteps, maxEpisodes, callbacks) } } // TODO: Support `boltzman(temperature:)`. public enum ProbabilisticAgentMode { case random case greedy case epsilonGreedy(_ epsilon: Float) case probabilistic } public protocol ProbabilisticAgent: Agent { associatedtype ActionDistribution: Distribution where ActionDistribution.Value == Action /// Generates the distribution over next actions given the current environment step. mutating func actionDistribution(for step: Step<Observation, Reward>) -> ActionDistribution } extension ProbabilisticAgent { @inlinable public mutating func action(for step: Step<Observation, Reward>) -> Action { action(for: step, mode: .greedy) } /// - Note: We cannot use a default argument value for `mode` here because of the `Agent` /// protocol requirement for an `Agent.action(for:)` function. @inlinable public mutating func action( for step: Step<Observation, Reward>, mode: ProbabilisticAgentMode ) -> Action { switch mode { case .random: return actionSpace.sample() case .greedy: return actionDistribution(for: step).mode() case let .epsilonGreedy(epsilon) where Float.random(in: 0..<1) < epsilon: return actionSpace.sample() case .epsilonGreedy(_): return actionDistribution(for: step).mode() case .probabilistic: return actionDistribution(for: step).sample() } } @inlinable public mutating func run( in environment: inout Environment, mode: ProbabilisticAgentMode = .greedy, maxSteps: Int = Int.max, maxEpisodes: Int = Int.max, callbacks: [StepCallback<Environment, State>] = [] ) throws { var currentStep = environment.currentStep var numSteps = 0 var numEpisodes = 0 while numSteps < maxSteps && numEpisodes < maxEpisodes { let action = self.action(for: currentStep, mode: mode) let nextStep = try environment.step(taking: action) var trajectory = Trajectory( stepKind: nextStep.kind, observation: currentStep.observation, state: state, action: action, reward: nextStep.reward) callbacks.forEach { $0(&environment, &trajectory) } numSteps += Int((1 - Tensor<Int32>(nextStep.kind.isLast())).sum().scalarized()) numEpisodes += Int(Tensor<Int32>(nextStep.kind.isLast()).sum().scalarized()) currentStep = nextStep } } } public struct AnyProbabilisticAgent< Environment: ReinforcementLearning.Environment, ActionDistribution: Distribution, State >: ProbabilisticAgent where ActionDistribution.Value == Environment.Action { public typealias Observation = Environment.Observation public typealias Action = Environment.Action public typealias Reward = Environment.Reward @usableFromInline internal let _actionSpace: () -> Environment.ActionSpace @usableFromInline internal let _getState: () -> State @usableFromInline internal let _setState: (State) -> Void @usableFromInline internal let _action: (Step<Observation, Reward>) -> Action @usableFromInline internal let _actionDistribution: ( Step<Observation, Reward> ) -> ActionDistribution @usableFromInline internal let _updateUsingTrajectory: ( Trajectory<Observation, State, Action, Reward> ) -> Float @usableFromInline internal let _updateUsingEnvironment: ( inout Environment, Int, Int, [StepCallback<Environment, State>] ) throws -> Float public var actionSpace: Environment.ActionSpace { _actionSpace() } public var state: State { get { _getState() } set { _setState(newValue) } } public init<A: ProbabilisticAgent>(_ agent: A) where A.Environment == Environment, A.ActionDistribution == ActionDistribution, A.State == State { var agent = agent _actionSpace = { () in agent.actionSpace } _getState = { () in agent.state } _setState = { agent.state = $0 } _action = { agent.action(for: $0) } _actionDistribution = { agent.actionDistribution(for: $0) } _updateUsingTrajectory = { agent.update(using: $0) } _updateUsingEnvironment = { try agent.update( using: &$0, maxSteps: $1, maxEpisodes: $2, callbacks: $3) } } @inlinable public mutating func action(for step: Step<Observation, Reward>) -> Action { _action(step) } @inlinable public mutating func actionDistribution( for step: Step<Observation, Reward> ) -> ActionDistribution { _actionDistribution(step) } @inlinable @discardableResult public mutating func update( using trajectory: Trajectory<Observation, State, Action, Reward> ) -> Float { _updateUsingTrajectory(trajectory) } @inlinable @discardableResult public mutating func update( using environment: inout Environment, maxSteps: Int = Int.max, maxEpisodes: Int = Int.max, callbacks: [StepCallback<Environment, State>] = [] ) throws -> Float { try _updateUsingEnvironment(&environment, maxSteps, maxEpisodes, callbacks) } } public struct RandomAgent<Environment: ReinforcementLearning.Environment>: ProbabilisticAgent { public typealias Observation = Environment.ObservationSpace.Value public typealias State = Empty public typealias Action = Environment.ActionSpace.Value public typealias ActionDistribution = Environment.ActionSpace.ValueDistribution public typealias Reward = Environment.Reward public let actionSpace: Environment.ActionSpace @inlinable public init(for environment: Environment) { actionSpace = environment.actionSpace } @inlinable public func actionDistribution(for step: Step<Observation, Reward>) -> ActionDistribution { actionSpace.distribution } @inlinable @discardableResult public mutating func update( using trajectory: Trajectory<Observation, State, Action, Reward> ) -> Float { 0.0 } @inlinable @discardableResult public mutating func update( using environment: inout Environment, maxSteps: Int, maxEpisodes: Int, callbacks: [StepCallback<Environment, State>] ) -> Float { 0.0 } }
apache-2.0
77bd75f858814af5eaecf24ce0792295
31.551546
99
0.703009
4.557921
false
false
false
false
cornerstonecollege/402
Younseo/GestureRecognizer/CustomViews/ViewController.swift
1
1378
// // ViewController.swift // CustomViews // // Created by hoconey on 2016/10/13. // Copyright © 2016年 younseo. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let frame = CGRect(x: 0, y: 50, width: 100, height: 100) let circle = FirstCustomView(frame: frame) //circle.backgroundColor = UIColor.red self.view.addSubview(circle) let frame2 = CGRect(x: 200, y: 50, width: 100, height: 100) let circle2 = FirstCustomView(frame: frame2) //circle.backgroundColor = UIColor.red self.view.addSubview(circle2) let frame3 = CGRect(x: 100, y: 250, width: 100, height: 200) let circle3 = FirstCustomView(frame: frame3) //circle.backgroundColor = UIColor.red self.view.addSubview(circle3) let circleFrame = CGRect(x: 100, y: 100, width: 100, height: 100) let circle4 = CircleView(frame: circleFrame) //circle4.backgroundColor = UIColor.yellow self.view.addSubview(circle4) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func panGesture(_ pan: UIPanGestureRecognizer){ pan.view!.center = pan.location(in: self.view) } }
gpl-3.0
219dafb574cc7584605724777172f564
26.5
73
0.619636
4.230769
false
false
false
false
brentsimmons/Evergreen
Shared/UserInfoKey.swift
1
964
// // UserInfoKey.swift // NetNewsWire // // Created by Maurice Parker on 11/14/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import Foundation struct UserInfoKey { static let webFeed = "webFeed" static let url = "url" static let articlePath = "articlePath" static let feedIdentifier = "feedIdentifier" static let windowState = "windowState" static let windowFullScreenState = "windowFullScreenState" static let containerExpandedWindowState = "containerExpandedWindowState" static let readFeedsFilterState = "readFeedsFilterState" static let readArticlesFilterState = "readArticlesFilterState" static let readArticlesFilterStateKeys = "readArticlesFilterStateKey" static let readArticlesFilterStateValues = "readArticlesFilterStateValue" static let selectedFeedsState = "selectedFeedsState" static let isShowingExtractedArticle = "isShowingExtractedArticle" static let articleWindowScrollY = "articleWindowScrollY" }
mit
d26f6984cce1697fd7abe973f55f089c
32.206897
74
0.803738
4.186957
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/RepeatingTimer.swift
4
1867
public class RepeatingTimer { private let source: DispatchSourceTimer private let semaphore: DispatchSemaphore = DispatchSemaphore(value: 1) private var isSet: Bool = true public init(_ intervalInSeconds: TimeInterval, afterDelay delayInSeconds: TimeInterval? = nil, leeway leewayInSeconds: TimeInterval? = nil, on queue: DispatchQueue = DispatchQueue.global(qos: .background), _ handler: @escaping () -> Void) { let interval = DispatchTimeInterval.nanoseconds(Int(intervalInSeconds * TimeInterval(NSEC_PER_SEC))) let delay: DispatchTimeInterval if let delayInSeconds = delayInSeconds { delay = DispatchTimeInterval.nanoseconds(Int(delayInSeconds * TimeInterval(NSEC_PER_SEC))) } else { delay = interval } let leeway: DispatchTimeInterval if let leewayInSeconds = leewayInSeconds { leeway = DispatchTimeInterval.nanoseconds(Int(leewayInSeconds * TimeInterval(NSEC_PER_SEC))) } else { leeway = DispatchTimeInterval.nanoseconds(Int(0.1 * intervalInSeconds * TimeInterval(NSEC_PER_SEC))) } self.source = DispatchSource.makeTimerSource(queue: queue) self.source.schedule(deadline: DispatchTime.now() + delay, repeating: interval, leeway: leeway) self.source.setEventHandler(handler: handler) self.source.resume() } public func resume() { semaphore.wait() defer { semaphore.signal() } guard !isSet else { return } isSet = true self.source.resume() } public func pause() { semaphore.wait() defer { semaphore.signal() } guard isSet else { return } isSet = false source.suspend() } }
mit
2950899268a3ef83fce8582d06bc8f95
34.226415
244
0.618104
5.288952
false
false
false
false
wortman/stroll_safe_ios
Stroll Safe/AppDelegate.swift
1
6601
// // AppDelegate.swift // Stroll Safe // // Created by Guest User (Mitchell) on 3/21/15. // Copyright (c) 2015 Stroll Safe. All rights reserved. // import UIKit import CoreData import UIKit import CoreData //import KeychainSwiftAPI @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // TODO check global variable for password // if password exists, continue to app // else, ask for password and store (hashed?) in variable // then go to pre-touch mode return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "edu.illinois.Stroll_Safe" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Stroll_Safe", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Stroll_Safe.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } }
apache-2.0
dbbd3b9054196d5b75204096e0470be7
49.776923
290
0.694137
5.74
false
false
false
false
mpullman/ios-charts
Charts/Classes/Renderers/D3PieChartRenderer.swift
1
5951
// // D3PieChartRenderer.swift // DataVis // // Created by Malcolm Pullman on 16/07/15. // Copyright (c) 2015 Datacom. All rights reserved. // import Foundation import CoreGraphics import UIKit public class D3PieChartRenderer: PieChartRenderer { internal override func drawDataSet(#context: CGContext, dataSet: PieChartDataSet) { var angle = _chart.rotationAngle var cnt = 0 var entries = dataSet.yVals var drawAngles = _chart.drawAngles var circleBox = _chart.circleBox var radius = _chart.radius var innerRadius = drawHoleEnabled && holeTransparent ? radius * holeRadiusPercent : 0.0 CGContextSaveGState(context) for (var j = 0; j < entries.count; j++) { var newangle = drawAngles[cnt] var sliceSpace = dataSet.sliceSpace var e = entries[j] // draw only if the value is greater than zero if ((abs(e.value) > 0.000001)) { if (!_chart.needsHighlight(xIndex: e.xIndex, dataSetIndex: _chart.data!.indexOfDataSet(dataSet))) { var startAngle = angle + sliceSpace / 2.0 var sweepAngle = newangle * _animator.phaseY - sliceSpace / 2.0 if (sweepAngle < 0.0) { sweepAngle = 0.0 } var endAngle = startAngle + sweepAngle var path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, circleBox.midX, circleBox.midY) CGPathAddArc(path, nil, circleBox.midX, circleBox.midY, radius, startAngle * ChartUtils.Math.FDEG2RAD, endAngle * ChartUtils.Math.FDEG2RAD, false) CGPathCloseSubpath(path) if (innerRadius > 0.0) { CGPathMoveToPoint(path, nil, circleBox.midX, circleBox.midY) CGPathAddArc(path, nil, circleBox.midX, circleBox.midY, innerRadius, startAngle * ChartUtils.Math.FDEG2RAD, endAngle * ChartUtils.Math.FDEG2RAD, false) CGPathCloseSubpath(path) } CGContextBeginPath(context) CGContextAddPath(context, path) CGContextSetFillColorWithColor(context, UIColor.lightGrayColor().CGColor) CGContextEOFillPath(context) } } angle += newangle * _animator.phaseX cnt++ } CGContextRestoreGState(context) } public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { if (_chart.data === nil) { return } CGContextSaveGState(context) var rotationAngle = _chart.rotationAngle var angle = CGFloat(0.0) var drawAngles = _chart.drawAngles var absoluteAngles = _chart.absoluteAngles var innerRadius = drawHoleEnabled && holeTransparent ? _chart.radius * holeRadiusPercent : 0.0 for (var i = 0; i < indices.count; i++) { // get the index to highlight var xIndex = indices[i].xIndex if (xIndex >= drawAngles.count) { continue } var set = _chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as! PieChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } if (xIndex == 0) { angle = rotationAngle } else { angle = rotationAngle + absoluteAngles[xIndex - 1] } angle *= _animator.phaseY var sliceDegrees = drawAngles[xIndex] var shift = set.selectionShift var circleBox = _chart.circleBox var highlighted = CGRect( x: circleBox.origin.x,// - shift, y: circleBox.origin.y,// - shift, width: circleBox.size.width,// + shift * 2.0, height: circleBox.size.height)// + shift * 2.0) CGContextSetFillColorWithColor(context, set.colorAt(xIndex).CGColor) // redefine the rect that contains the arc so that the highlighted pie is not cut off var startAngle = angle + set.sliceSpace / 2.0 var sweepAngle = sliceDegrees * _animator.phaseY - set.sliceSpace / 2.0 if (sweepAngle < 0.0) { sweepAngle = 0.0 } var endAngle = startAngle + sweepAngle var path = CGPathCreateMutable() CGPathMoveToPoint(path, nil, highlighted.midX, highlighted.midY) CGPathAddArc(path, nil, highlighted.midX, highlighted.midY, highlighted.size.width / 2.0, startAngle * ChartUtils.Math.FDEG2RAD, endAngle * ChartUtils.Math.FDEG2RAD, false) CGPathCloseSubpath(path) if (innerRadius > 0.0) { CGPathMoveToPoint(path, nil, highlighted.midX, highlighted.midY) CGPathAddArc(path, nil, highlighted.midX, highlighted.midY, innerRadius, startAngle * ChartUtils.Math.FDEG2RAD, endAngle * ChartUtils.Math.FDEG2RAD, false) CGPathCloseSubpath(path) } CGContextBeginPath(context) CGContextAddPath(context, path) CGContextEOFillPath(context) } CGContextRestoreGState(context) } }
apache-2.0
70e56a73ef7b268c71c106fda1db3d47
35.292683
184
0.521425
5.505088
false
false
false
false
JGiola/swift-package-manager
Sources/PackageDescription4/SupportedPlatforms.swift
1
7894
/* This source file is part of the Swift.org open source project Copyright (c) 2018 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// Represents a platform. public struct Platform: Encodable { /// The name of the platform. fileprivate let name: String private init(name: String) { self.name = name } public static let macOS: Platform = Platform(name: "macos") public static let iOS: Platform = Platform(name: "ios") public static let tvOS: Platform = Platform(name: "tvos") public static let watchOS: Platform = Platform(name: "watchos") public static let linux: Platform = Platform(name: "linux") } /// Represents a platform supported by the package. public struct SupportedPlatform: Encodable { /// The platform. let platform: Platform /// The platform version. let version: VersionedValue<String>? /// Creates supported platform instance. init(platform: Platform, version: VersionedValue<String>? = nil) { self.platform = platform self.version = version } /// Create macOS supported platform with the given version. public static func macOS(_ version: SupportedPlatform.MacOSVersion) -> SupportedPlatform { return SupportedPlatform(platform: .macOS, version: version.version) } /// Create macOS supported platform with the given version string. /// /// The version string must be a series of 2 or 3 dot-separated integers, for example "10.10" or "10.10.1". public static func macOS(_ versionString: String) -> SupportedPlatform { return SupportedPlatform(platform: .macOS, version: SupportedPlatform.MacOSVersion(versionString).version) } /// Create iOS supported platform with the given version. public static func iOS(_ version: SupportedPlatform.IOSVersion) -> SupportedPlatform { return SupportedPlatform(platform: .iOS, version: version.version) } /// Create iOS supported platform with the given version string. /// /// The version string must be a series of 2 or 3 dot-separated integers, for example "8.0" or "8.0.1". public static func iOS(_ versionString: String) -> SupportedPlatform { return SupportedPlatform(platform: .iOS, version: SupportedPlatform.IOSVersion(versionString).version) } /// Create tvOS supported platform with the given version. public static func tvOS(_ version: SupportedPlatform.TVOSVersion) -> SupportedPlatform { return SupportedPlatform(platform: .tvOS, version: version.version) } /// Create tvOS supported platform with the given version string. /// /// The version string must be a series of 2 or 3 dot-separated integers, for example "9.0" or "9.0.1". public static func tvOS(_ versionString: String) -> SupportedPlatform { return SupportedPlatform(platform: .tvOS, version: SupportedPlatform.TVOSVersion(versionString).version) } /// Create watchOS supported platform with the given version. public static func watchOS(_ version: SupportedPlatform.WatchOSVersion) -> SupportedPlatform { return SupportedPlatform(platform: .watchOS, version: version.version) } /// Create watchOS supported platform with the given version string. /// /// The version string must be a series of 2 or 3 dot-separated integers, for example "2.0" or "2.0.1". public static func watchOS(_ versionString: String) -> SupportedPlatform { return SupportedPlatform(platform: .watchOS, version: SupportedPlatform.WatchOSVersion(versionString).version) } } extension SupportedPlatform { /// The macOS version. public struct MacOSVersion: Encodable, AppleOSVersion { fileprivate static let name = "macOS" fileprivate static let minimumMajorVersion = 10 /// The underlying version representation. let version: VersionedValue<String> fileprivate init(_ version: VersionedValue<String>) { self.version = version } public static let v10_10: MacOSVersion = .init("10.10", supportedVersions: [.v5]) public static let v10_11: MacOSVersion = .init("10.11", supportedVersions: [.v5]) public static let v10_12: MacOSVersion = .init("10.12", supportedVersions: [.v5]) public static let v10_13: MacOSVersion = .init("10.13", supportedVersions: [.v5]) public static let v10_14: MacOSVersion = .init("10.14", supportedVersions: [.v5]) } public struct TVOSVersion: Encodable, AppleOSVersion { fileprivate static let name = "tvOS" fileprivate static let minimumMajorVersion = 9 /// The underlying version representation. let version: VersionedValue<String> fileprivate init(_ version: VersionedValue<String>) { self.version = version } public static let v9: TVOSVersion = .init("9.0", supportedVersions: [.v5]) public static let v10: TVOSVersion = .init("10.0", supportedVersions: [.v5]) public static let v11: TVOSVersion = .init("11.0", supportedVersions: [.v5]) public static let v12: TVOSVersion = .init("12.0", supportedVersions: [.v5]) } public struct IOSVersion: Encodable, AppleOSVersion { fileprivate static let name = "iOS" fileprivate static let minimumMajorVersion = 2 /// The underlying version representation. let version: VersionedValue<String> fileprivate init(_ version: VersionedValue<String>) { self.version = version } public static let v8: IOSVersion = .init("8.0", supportedVersions: [.v5]) public static let v9: IOSVersion = .init("9.0", supportedVersions: [.v5]) public static let v10: IOSVersion = .init("10.0", supportedVersions: [.v5]) public static let v11: IOSVersion = .init("11.0", supportedVersions: [.v5]) public static let v12: IOSVersion = .init("12.0", supportedVersions: [.v5]) } public struct WatchOSVersion: Encodable, AppleOSVersion { fileprivate static let name = "watchOS" fileprivate static let minimumMajorVersion = 2 /// The underlying version representation. let version: VersionedValue<String> fileprivate init(_ version: VersionedValue<String>) { self.version = version } public static let v2: WatchOSVersion = .init("2.0", supportedVersions: [.v5]) public static let v3: WatchOSVersion = .init("3.0", supportedVersions: [.v5]) public static let v4: WatchOSVersion = .init("4.0", supportedVersions: [.v5]) public static let v5: WatchOSVersion = .init("5.0", supportedVersions: [.v5]) } } fileprivate protocol AppleOSVersion { static var name: String { get } static var minimumMajorVersion: Int { get } init(_ version: VersionedValue<String>) } fileprivate extension AppleOSVersion { init(_ version: String, supportedVersions: [ManifestVersion]) { let api = "v" + version.split(separator: ".").reversed().drop(while: { $0 == "0" }).reversed().joined(separator: "_") self.init(VersionedValue(version, api: api, versions: supportedVersions)) } init(_ string: String) { // Perform a quick validation. let components = string.split(separator: ".", omittingEmptySubsequences: false).map({ UInt($0) }) var error = components.compactMap({ $0 }).count != components.count error = error || !(components.count == 2 || components.count == 3) || ((components[0] ?? 0) < Self.minimumMajorVersion) if error { errors.append("invalid \(Self.name) version string: \(string)") } self.init(VersionedValue(string, api: "")) } }
apache-2.0
fb0b09c288ab9d6a2dd45f255dcc1af8
40.989362
127
0.67583
4.684866
false
false
false
false
benlangmuir/swift
test/decl/subscript/static.swift
30
1350
// RUN: %target-typecheck-verify-swift struct MyStruct { static subscript(_ i: Int) -> String { get { return "get \(i)" } set { print("set \(i) = \(newValue)") } } } func useMyStruct() { print(MyStruct.self[0]) print(MyStruct[0]) MyStruct.self[1] = "zyzyx" MyStruct[2] = "asdfg" MyStruct()[0] // expected-error {{static member 'subscript' cannot be used on instance of type 'MyStruct'}} MyStruct()[1] = "zyzyx" // expected-error {{static member 'subscript' cannot be used on instance of type 'MyStruct'}} } struct BadStruct { static subscript(_ i: Int) -> String { nonmutating get { fatalError() } // expected-error{{static functions must not be declared mutating}} mutating set { fatalError() } // expected-error{{static functions must not be declared mutating}} } } @dynamicMemberLookup class Dyn { static subscript(dynamicMember name: String) -> String { return "Dyn.\(name)" } } func useDyn() { _ = Dyn.foo _ = Dyn().bar // expected-error{{static member 'bar' cannot be used on instance of type 'Dyn'}} } class BadBase { static subscript(_ i: Int) -> String { return "Base" } // expected-note{{overridden declaration is here}} } class BadDerived: BadBase { override static subscript(_ i: Int) -> String { return "DerivedGood" } // expected-error{{cannot override static subscript}} }
apache-2.0
b51a927b822b11f017478d1c8df68d13
29
126
0.665926
3.668478
false
false
false
false
Tim77277/WizardUIKit
WizardUIKit/ActionAlertViewController.swift
1
7907
/********************************************************** MIT License WizardUIKit Copyright (c) 2016 Wei-Ting Lin 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 ActionAlertViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { //MARK: - Custom Delegate typealias CancelDelegate = () -> () typealias ActionDelegate = () -> () var didCancel: CancelDelegate? var didConfirmAction: ActionDelegate? //MARK: - Variables var actionAlert: WizardActionAlert! //MARK: - IBOutlets @IBOutlet weak var alertTitleLabel: UILabel! @IBOutlet weak var alertTableView: UITableView! @IBOutlet weak var alertActionButton: UIButton! @IBOutlet weak var alertCancelButton: UIButton! @IBOutlet weak var alertView: UIView! @IBOutlet weak var alertViewHeightConstraint: NSLayoutConstraint! @IBOutlet weak var gapViewHeightConstraint: NSLayoutConstraint! //MARK: - UIViewController Life Cycle override func viewDidLoad() { super.viewDidLoad() tableViewConfiguration() initializeActionAlertWith(actionAlert: actionAlert) // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) view.layoutIfNeeded() showAlertAnimationWith(options: actionAlert.animation) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: UITableView Delegate / DataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "WizardAlertTextCell", for: indexPath) as! WizardAlertTextCell cell.contentTextLabel.font = actionAlert.contentLabel.font cell.contentTextLabel.textAlignment = actionAlert.contentLabel.textAlignment cell.contentTextLabel.text = actionAlert.contentLabel.text cell.contentTextLabel.textColor = actionAlert.contentLabel.textColor cell.backgroundColor = .clear cell.contentView.backgroundColor = .clear cell.selectionStyle = .none return cell } //MARK: - IBActions @IBAction func alertCancelButtonTapped(_ sender: AnyObject) { if didCancel != nil { self.didCancel!() } } @IBAction func alertActionButtonTapped(_ sender: AnyObject) { if didConfirmAction != nil { self.didConfirmAction!() } } //MARK: - Animations private func showAlertAnimationWith(options: WizardAnimation) { //Handle expandable if actionAlert.expandable && alertTableView.contentSize.height > 20 { //New height = height of the content text + other objects heigh in alertView let newHeight = alertView.frame.height + alertTableView.contentSize.height - alertTableView.frame.height let kAlertTextMaximumHeight = view.frame.height * 0.8 if newHeight > kAlertTextMaximumHeight { alertViewHeightConstraint.constant = kAlertTextMaximumHeight } else if newHeight > kAlertTextMinimumHeight && newHeight <= kAlertTextMaximumHeight { alertViewHeightConstraint.constant = newHeight } } //Optimize lable position let numOfLines = alertTableView.contentSize.height / actionAlert.contentLabel.font.lineHeight if numOfLines <= 2 { gapViewHeightConstraint.constant = 20 } //Animate alert view switch options.direction { case .fadeIn: alertView.alpha = 0.0 UIView.animate(withDuration: options.duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: .curveEaseIn, animations: { self.alertView.alpha = 1.0 }, completion: nil) case .slideDown: alertView.transform = CGAffineTransform(translationX: 0, y: -500) UIView.animate(withDuration: options.duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: .curveEaseIn, animations: { self.alertView.transform = CGAffineTransform(translationX: 0, y: 0) }, completion: nil) case .slideUp: alertView.transform = CGAffineTransform(translationX: 0, y: 500) UIView.animate(withDuration: options.duration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: .curveEaseIn, animations: { self.alertView.transform = CGAffineTransform(translationX: 0, y: 0) }, completion: nil) } } //MARK: - Initialization private func initializeActionAlertWith(actionAlert: WizardActionAlert) { alertTitleLabel.text = actionAlert.titleLabel.text alertTitleLabel.textColor = actionAlert.titleLabel.textColor alertTitleLabel.font = actionAlert.titleLabel.font alertView.backgroundColor = actionAlert.backgroundColor if let cancelButtonOptions = actionAlert.cancelButton { alertCancelButton.setTitle(cancelButtonOptions.text, for: .normal) alertCancelButton.setTitleColor(cancelButtonOptions.textColor, for: .normal) alertCancelButton.layer.cornerRadius = cancelButtonOptions.cornerRadius alertCancelButton.backgroundColor = cancelButtonOptions.backgroundColor } if let actionButtonOptions = actionAlert.actionButton { alertActionButton.setTitle(actionButtonOptions.text, for: .normal) alertActionButton.setTitleColor(actionButtonOptions.textColor, for: .normal) alertActionButton.layer.cornerRadius = actionButtonOptions.cornerRadius alertActionButton.backgroundColor = actionButtonOptions.backgroundColor } //Not yet public properties alertView.layer.cornerRadius = 5 view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) } private func tableViewConfiguration() { alertTableView.rowHeight = UITableViewAutomaticDimension alertTableView.estimatedRowHeight = 300 alertTableView.delegate = self alertTableView.dataSource = self alertTableView.separatorColor = .clear alertTableView.register(UINib(nibName: "WizardAlertTextCell", bundle: kWizardBundle), forCellReuseIdentifier: "WizardAlertTextCell") } }
mit
8beac562b1f391efeb0ad04a3bab0476
42.927778
162
0.682307
5.572234
false
false
false
false
nst/JSONTestSuite
parsers/test_json_swift_20170522/JSONLib/JSValue.Indexers.swift
1
2343
/* -------------------------------------------------------------------------------------------- * Copyright (c) Kiad Studios, LLC. All rights reserved. * Licensed under the MIT License. See License in the project root for license information. * ------------------------------------------------------------------------------------------ */ extension JSValue { /// Attempts to treat the `JSValue` as a `JSObject` and perform the lookup. /// /// - returns: A `JSValue` that represents the value found at `key` public subscript(key: String) -> JSValue? { get { if let dict = self.object { if let value = dict[key] { return value } } return nil } set { if var dict = self.object { dict[key] = newValue self = JSValue(dict) } } } /// Attempts to treat the `JSValue` as an array and return the item at the index. public subscript(index: Int) -> JSValue? { get { if let array = self.array { if index >= 0 && index < array.count { return array[index] } } return nil } set { if var array = self.array { array[index] = newValue ?? .null self = JSValue(array) } } } } /* /// Provide a usability extension to allow chaining index accessors without having to /// marked it as optional. /// e.g. foo["hi"]?["this"]?["sucks"] vs. foo["so"]["much"]["better"] extension Optional where Wrapped == JSValue { public subscript(key: String) -> JSValue? { get { return self?.object?[key] } set { if var dict = self?.object { dict[key] = newValue self = JSValue(dict) } } } /// Attempts to treat the `JSValue` as an array and return the item at the index. public subscript(index: Int) -> JSValue? { get { return self?.array?[index] } set { if var array = self?.array { array[index] = newValue ?? .null self = JSValue(array) } } } } */
mit
5d68d18774a78325a4b92f2dda363dce
29.428571
96
0.439181
4.953488
false
false
false
false
SeraZheng/GitHouse.swift
GitHouse/IssueViewController.swift
1
2867
// // IssueViewController.swift // GitHouse // // Created by 郑少博 on 16/4/13. // Copyright © 2016年 郑少博. All rights reserved. // // // RepositoriesViewController.swift // GitHouse // // Created by 郑少博 on 16/3/28. // Copyright © 2016年 郑少博. All rights reserved. // import UIKit import Octokit import AlamofireImage class IssuesViewController: BaseViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.refreshEnabled = true self.tabBarItem = UITabBarItem(title: "Issues".localized(), image: UIImage.octiconsImageFor(OcticonsID.IssueOpened, iconColor: UIColor.flatGrayColor(), size: CGSizeMake(25, 25)), selectedImage: UIImage.octiconsImageFor(OcticonsID.IssueOpened, iconColor: UIColor.flatBlueColor(), size: CGSizeMake(25, 25))) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() title = "Issues".localized() tableView.estimatedRowHeight = 70 tableView.rowHeight = UITableViewAutomaticDimension KRProgressHUD.show() GitHouseUtils.isHomeLoaded = true } } //MARK: BaseModeProtocol extension IssuesViewController { override func loadData() { GitHouseUtils.octokit?.myIssues(completion: { [weak self] (response) in guard let strongSelf = self else { return } switch response { case .Success( let issues): strongSelf.allItems = issues dispatch_async(dispatch_get_main_queue(), { KRProgressHUD.dismiss() strongSelf.tableView.reloadData() }) case .Failure( _): dispatch_async(dispatch_get_main_queue(), { KRProgressHUD.dismiss() strongSelf.modelDelegate?.showError!() }) } }) } } //MARK: UITableViewDataSource, UITableViewDelegate extension IssuesViewController { override func cellClass() -> UITableViewCell.Type { return IssueTableCell.self } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allItems.count } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { let issue: Issue = allItems[indexPath.row] as! Issue (cell as! IssueTableCell).configCell(issue) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70 } }
mit
373ba50792b98be57a2cd9033a61a239
29.505376
165
0.632358
5.003527
false
false
false
false
noppefoxwolf/TVUploader-iOS
Example/Pods/SwiftTask/SwiftTask/_StateMachine.swift
1
8282
// // _StateMachine.swift // SwiftTask // // Created by Yasuhiro Inami on 2015/01/21. // Copyright (c) 2015年 Yasuhiro Inami. All rights reserved. // import Foundation /// /// fast, naive event-handler-manager in replace of ReactKit/SwiftState (dynamic but slow), /// introduced from SwiftTask 2.6.0 /// /// see also: https://github.com/ReactKit/SwiftTask/pull/22 /// internal class _StateMachine<Progress, Value, Error> { internal typealias ErrorInfo = Task<Progress, Value, Error>.ErrorInfo internal typealias ProgressTupleHandler = Task<Progress, Value, Error>._ProgressTupleHandler internal let weakified: Bool internal let state: _Atomic<TaskState> internal let progress: _Atomic<Progress?> = _Atomic(nil) // NOTE: always nil if `weakified = true` internal let value: _Atomic<Value?> = _Atomic(nil) internal let errorInfo: _Atomic<ErrorInfo?> = _Atomic(nil) internal let configuration = TaskConfiguration() /// wrapper closure for `_initClosure` to invoke only once when started `.Running`, /// and will be set to `nil` afterward internal var initResumeClosure: _Atomic<(Void -> Void)?> = _Atomic(nil) private lazy var _progressTupleHandlers = _Handlers<ProgressTupleHandler>() private lazy var _completionHandlers = _Handlers<Void -> Void>() private var _lock = _RecursiveLock() internal init(weakified: Bool, paused: Bool) { self.weakified = weakified self.state = _Atomic(paused ? .Paused : .Running) } internal func addProgressTupleHandler(inout token: _HandlerToken?, _ progressTupleHandler: ProgressTupleHandler) -> Bool { self._lock.lock() defer { self._lock.unlock() } if self.state.rawValue == .Running || self.state.rawValue == .Paused { token = self._progressTupleHandlers.append(progressTupleHandler) return token != nil } else { return false } } internal func removeProgressTupleHandler(handlerToken: _HandlerToken?) -> Bool { self._lock.lock() defer { self._lock.unlock() } if let handlerToken = handlerToken { let removedHandler = self._progressTupleHandlers.remove(handlerToken) return removedHandler != nil } else { return false } } internal func addCompletionHandler(inout token: _HandlerToken?, _ completionHandler: Void -> Void) -> Bool { self._lock.lock() defer { self._lock.unlock() } if self.state.rawValue == .Running || self.state.rawValue == .Paused { token = self._completionHandlers.append(completionHandler) return token != nil } else { return false } } internal func removeCompletionHandler(handlerToken: _HandlerToken?) -> Bool { self._lock.lock() defer { self._lock.unlock() } if let handlerToken = handlerToken { let removedHandler = self._completionHandlers.remove(handlerToken) return removedHandler != nil } else { return false } } internal func handleProgress(progress: Progress) { self._lock.lock() defer { self._lock.unlock() } if self.state.rawValue == .Running { let oldProgress = self.progress.rawValue // NOTE: if `weakified = false`, don't store progressValue for less memory footprint if !self.weakified { self.progress.rawValue = progress } for handler in self._progressTupleHandlers { handler(oldProgress: oldProgress, newProgress: progress) } } } internal func handleFulfill(value: Value) { self._lock.lock() defer { self._lock.unlock() } let newState = self.state.updateIf { $0 == .Running ? .Fulfilled : nil } if let _ = newState { self.value.rawValue = value self._finish() } } internal func handleRejectInfo(errorInfo: ErrorInfo) { self._lock.lock() defer { self._lock.unlock() } let toState = errorInfo.isCancelled ? TaskState.Cancelled : .Rejected let newState = self.state.updateIf { $0 == .Running || $0 == .Paused ? toState : nil } if let _ = newState { self.errorInfo.rawValue = errorInfo self._finish() } } internal func handlePause() -> Bool { self._lock.lock() defer { self._lock.unlock() } let newState = self.state.updateIf { $0 == .Running ? .Paused : nil } if let _ = newState { self.configuration.pause?() return true } else { return false } } internal func handleResume() -> Bool { self._lock.lock() if let initResumeClosure = self.initResumeClosure.update({ _ in nil }) { self.state.rawValue = .Running self._lock.unlock() // // NOTE: // Don't use `_lock` here so that dispatch_async'ed `handleProgress` inside `initResumeClosure()` // will be safely called even when current thread goes into sleep. // initResumeClosure() // // Comment-Out: // Don't call `configuration.resume()` when lazy starting. // This prevents inapropriate starting of upstream in ReactKit. // //self.configuration.resume?() return true } else { let resumed = _handleResume() self._lock.unlock() return resumed } } private func _handleResume() -> Bool { let newState = self.state.updateIf { $0 == .Paused ? .Running : nil } if let _ = newState { self.configuration.resume?() return true } else { return false } } internal func handleCancel(error: Error? = nil) -> Bool { self._lock.lock() defer { self._lock.unlock() } let newState = self.state.updateIf { $0 == .Running || $0 == .Paused ? .Cancelled : nil } if let _ = newState { self.errorInfo.rawValue = ErrorInfo(error: error, isCancelled: true) self._finish() return true } else { return false } } private func _finish() { for handler in self._completionHandlers { handler() } self._progressTupleHandlers.removeAll() self._completionHandlers.removeAll() self.configuration.finish() self.initResumeClosure.rawValue = nil self.progress.rawValue = nil } } //-------------------------------------------------- // MARK: - Utility //-------------------------------------------------- internal struct _HandlerToken { internal let key: Int } internal struct _Handlers<T>: SequenceType { internal typealias KeyValue = (key: Int, value: T) private var currentKey: Int = 0 private var elements = [KeyValue]() internal mutating func append(value: T) -> _HandlerToken { self.currentKey = self.currentKey &+ 1 self.elements += [(key: self.currentKey, value: value)] return _HandlerToken(key: self.currentKey) } internal mutating func remove(token: _HandlerToken) -> T? { for i in 0..<self.elements.count { if self.elements[i].key == token.key { return self.elements.removeAtIndex(i).value } } return nil } internal mutating func removeAll(keepCapacity: Bool = false) { self.elements.removeAll(keepCapacity: keepCapacity) } internal func generate() -> AnyGenerator<T> { return AnyGenerator(self.elements.map { $0.value }.generate()) } }
mit
e50c1accf858261f422804687696aeb8
28.365248
124
0.550725
4.972973
false
false
false
false
Scorocode/scorocode-SDK-swift
todolist/HistoryCell.swift
1
785
// // HistoryCell.swift // todolist // // Created by Alexey Kuznetsov on 09/11/2016. // Copyright © 2016 ProfIT. All rights reserved. // import UIKit class HistoryCell : UITableViewCell { @IBOutlet weak var labelDate: UILabel! @IBOutlet weak var labelField: UILabel! @IBOutlet weak var labelValue: UILabel! func setCell(_ date: Date, field: String, value: String) { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone.autoupdatingCurrent dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" let dateObj = dateFormatter.string(from: date) self.labelDate.text = dateObj self.labelField.text = field self.labelValue.text = value self.isUserInteractionEnabled = false } }
mit
b494b327b20e722773f547846b21b3b8
27
62
0.668367
4.355556
false
false
false
false
dinsight/AxiomKit
Sources/AXFact.swift
1
1054
// // PMFact.swift // PuppetMasterKit // // Created by Alexandru Cotoman Jecu on 5/3/17. // Copyright © 2017 Digital Insight, LLC. All rights reserved. // import Foundation open class AXFact { public var grade: Float = 0 /** Initialization */ public init(){ } /** Sets the grade of the fact - Parameter grade: The grade of the fact */ @discardableResult public func withGrade(grade: Float) -> AXFact { self.grade = grade return self } /** Object Id */ public func getTypeString() -> String { return String(describing: self) } } extension AXFact : Equatable{ open static func ==(lhs: AXFact, rhs: AXFact) -> Bool { print("Comparing with == operator") return lhs.getTypeString() == rhs.getTypeString() } open static func !=(lhs: AXFact, rhs: AXFact) -> Bool { print("Comparing with != operator") return !(lhs == rhs) } }
mit
69c126d0c8d091a0f9b274a2bac30552
17.155172
63
0.54321
4.280488
false
false
false
false
gmilos/swift
test/Constraints/lvalues.swift
3
8242
// RUN: %target-typecheck-verify-swift func f0(_ x: inout Int) {} func f1<T>(_ x: inout T) {} func f2(_ x: inout X) {} func f2(_ x: inout Double) {} class Reftype { var property: Double { get {} set {} } } struct X { subscript(i: Int) -> Float { get {} set {} } var property: Double { get {} set {} } func genuflect() {} } struct Y { subscript(i: Int) -> Float { get {} set {} } subscript(f: Float) -> Int { get {} set {} } } var i : Int var f : Float var x : X var y : Y func +=(lhs: inout X, rhs : X) {} func +=(lhs: inout Double, rhs : Double) {} prefix func ++(rhs: inout X) {} postfix func ++(lhs: inout X) {} f0(&i) f1(&i) f1(&x[i]) f1(&x.property) f1(&y[i]) // Missing '&' f0(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{4-4=&}} f1(y[i]) // expected-error{{passing value of type 'Float' to an inout parameter requires explicit '&'}} {{4-4=&}} // Assignment operators x += x ++x var yi = y[i] // Non-settable lvalues var non_settable_x : X { return x } struct Z { var non_settable_x: X { get {} } var non_settable_reftype: Reftype { get {} } var settable_x : X subscript(i: Int) -> Double { get {} } subscript(_: (i: Int, j: Int)) -> X { get {} } } var z : Z func fz() -> Z {} func fref() -> Reftype {} // non-settable var is non-settable: // - assignment non_settable_x = x // expected-error{{cannot assign to value: 'non_settable_x' is a get-only property}} // - inout (mono) f2(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout (generic) f1(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout assignment non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++non_settable_x // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // non-settable property is non-settable: z.non_settable_x = x // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++z.non_settable_x // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // non-settable subscript is non-settable: z[0] = 0.0 // expected-error{{cannot assign through subscript: subscript is get-only}} f2(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} f1(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} z[0] += 0.0 // expected-error{{left side of mutating operator isn't mutable: subscript is get-only}} ++z[0] // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} // settable property of an rvalue value type is non-settable: fz().settable_x = x // expected-error{{cannot assign to property: 'fz' returns immutable value}} f2(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} f1(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} fz().settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'fz' returns immutable value}} ++fz().settable_x // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} // settable property of an rvalue reference type IS SETTABLE: fref().property = 0.0 f2(&fref().property) f1(&fref().property) fref().property += 0.0 fref().property += 1 // settable property of a non-settable value type is non-settable: z.non_settable_x.property = 1.0 // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x.property += 1.0 // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++z.non_settable_x.property // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // settable property of a non-settable reference type IS SETTABLE: z.non_settable_reftype.property = 1.0 f2(&z.non_settable_reftype.property) f1(&z.non_settable_reftype.property) z.non_settable_reftype.property += 1.0 z.non_settable_reftype.property += 1 // regressions with non-settable subscripts in value contexts _ = z[0] == 0 var d : Double d = z[0] // regressions with subscripts that return generic types var xs:[X] _ = xs[0].property struct A<T> { subscript(i: Int) -> T { get {} } } struct B { subscript(i: Int) -> Int { get {} } } var a:A<B> _ = a[0][0] // Instance members of struct metatypes. struct FooStruct { func instanceFunc0() {} } func testFooStruct() { FooStruct.instanceFunc0(FooStruct())() } // Don't load from explicit lvalues. func takesInt(_ x: Int) {} func testInOut(_ arg: inout Int) { var x : Int takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} } // Don't infer inout types. var ir = &i // expected-error{{type 'inout Int' of variable is not materializable}} \ // expected-error{{'&' can only appear immediately in a call argument list}} var ir2 = ((&i)) // expected-error{{type 'inout Int' of variable is not materializable}} \ // expected-error{{'&' can only appear immediately in a call argument list}} // <rdar://problem/17133089> func takeArrayRef(_ x: inout Array<String>) { } // rdar://22308291 takeArrayRef(["asdf", "1234"]) // expected-error{{contextual type 'inout Array<String>' cannot be used with array literal}} // <rdar://problem/19835413> Reference to value from array changed func rdar19835413() { func f1(_ p: UnsafeMutableRawPointer) {} func f2(_ a: [Int], i: Int, pi: UnsafeMutablePointer<Int>) { var a = a f1(&a) f1(&a[i]) f1(&a[0]) f1(pi) f1(pi) } } // <rdar://problem/21877598> Crash when accessing stored property without // setter from constructor protocol Radish { var root: Int { get } } public struct Kale : Radish { public let root : Int public init() { let _ = Kale().root self.root = 0 } } func testImmutableUnsafePointer(_ p: UnsafePointer<Int>) { p.pointee = 1 // expected-error {{cannot assign to property: 'pointee' is a get-only property}} p[0] = 1 // expected-error {{cannot assign through subscript: subscript is get-only}} } // <https://bugs.swift.org/browse/SR-7> Inferring closure param type to // inout crashes compiler let g = { x in f0(x) } // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{19-19=&}} // <rdar://problem/17245353> Crash with optional closure taking inout func rdar17245353() { typealias Fn = (inout Int) -> () func getFn() -> Fn? { return nil } let _: (inout UInt, UInt) -> Void = { $0 += $1 } } // <rdar://problem/23131768> Bugs related to closures with inout parameters func rdar23131768() { func f(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f { $0 += 1 } // Crashes compiler func f2(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f2 { $0 = $0 + 1 } // previously error: Cannot convert value of type '_ -> ()' to expected type '(inout Int) -> Void' func f3(_ g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f3 { (v: inout Int) -> Void in v += 1 } } // <rdar://problem/23331567> Swift: Compiler crash related to closures with inout parameter. func r23331567(_ fn: (_ x: inout Int) -> Void) { var a = 0 fn(&a) } r23331567 { $0 += 1 }
apache-2.0
3da1a73dc8d4115081393d69cf284789
34.07234
139
0.670226
3.275835
false
false
false
false
idrisyildiz7/Simple-Calculator
Deneme/ViewController.swift
1
4244
import UIKit class ViewController: UIViewController { @IBOutlet weak var historyLb: UILabel! @IBOutlet weak var myLabel: UILabel! var operant:String = "" var islemFlag:Int = 0 //flag for 2nd operant var historyText:String? var flagEqualClicked:Bool = false var resultText:String = "" override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func Clear(sender: AnyObject) { myLabel.text = "" historyLb.text = "" islemFlag = 0 operant = "" flagEqualClicked=false } @IBAction func onClick(sender: AnyObject) { if historyText == nil { historyText = "" } resultText = myLabel.text! let click:Int = sender.tag if click >= 0 && click < 10 { //writing numbers if flagEqualClicked && islemFlag == 0 { flagEqualClicked=false resultText = "" } myLabel.text = "" + resultText + "\(click)" } else if click == 11 // sum operation { islemControl("+") } else if click == 12 // subtraction operation { islemControl("-") } else if click == 13 // multiplaction operation { islemControl("*") } else if click == 14 // division operation { islemControl("/") } else if click == 15 && islemFlag == 1 // for clicking equal button { flagEqualClicked=true historyLb.text = resultText let result:Int = parsing(resultText) historyText = historyText! + resultText + "=" + "\(result) \n" myLabel.text = "\(result)" islemFlag = 0 } } func calculater(num1: Int, num2: Int) -> Int { var result:Int = 0 if operant == "+" { result = num1 + num2 } if operant == "-" { result = num1 - num2 } if operant == "*" { result = num1 * num2 } if operant == "/" { result = num1 / num2 } return result } func parsing(text: String) -> Int { let numberArr = text.componentsSeparatedByString(operant) let firstNum: String = numberArr[0] let secondNum: String = numberArr[1] let num1:Int = Int(firstNum)! let num2:Int = Int(secondNum)! let result:Int = calculater(num1,num2: num2) islemFlag = 1 return result } func islemControl(islem: String) { if islastCharIsOperant() { let test:String = myLabel.text! let endIndex = test.endIndex.advancedBy(-1) let newLabel = test.substringToIndex(endIndex) myLabel.text = newLabel resultText = myLabel.text! islemFlag = 0 } islemFlag++ if islemFlag == 2 { historyLb.text = resultText let result:Int = parsing(resultText) historyText = historyText! + resultText + "=" + "\(result) \n" myLabel.text = "\(result)" resultText = myLabel.text! } operant = islem myLabel.text = "" + resultText + operant } func islastCharIsOperant() -> Bool { let test:String = myLabel.text! let endIndex = test.endIndex.advancedBy(-1) let lastChar = test.substringFromIndex(endIndex) if lastChar == "+" || lastChar == "-" || lastChar == "*" || lastChar == "/" { return true } return false } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { let controller = segue.destinationViewController as! ViewController2 controller.textV2 = historyText } }
apache-2.0
ac7414b5a3a4a52659619d236899adb5
24.413174
83
0.490339
5.156744
false
false
false
false
BalestraPatrick/Tweetometer
Tweetometer/UserDetailsTableViewCell.swift
2
2305
// // UserDetailsTableViewCell.swift // TweetsCounter // // Created by Patrick Balestra on 5/1/16. // Copyright © 2016 Patrick Balestra. All rights reserved. // import UIKit import TweetometerKit //import ActiveLabel class UserDetailsTableViewCell: UITableViewCell { @IBOutlet weak var profileImage: ProfilePictureImageView! // @IBOutlet weak var descriptionLabel: ActiveLabel! @IBOutlet weak var totalTweetsCountLabel: UILabel! @IBOutlet weak var tweetsCountLabel: UILabel! @IBOutlet weak var retweetsCountLabel: UILabel! @IBOutlet weak var repliesCountLabel: UILabel! weak var coordinator: UserDetailCoordinator! var totalTweetsCount: Int = 0 { didSet { totalTweetsCountLabel.attributedText = NSAttributedString.totalTweetsCountAttributes(with: totalTweetsCount) } } var tweetsCount: Int = 0 { didSet { tweetsCountLabel.attributedText = NSAttributedString.tweetsCountAttributes(with: tweetsCount) } } var retweetsCount: Int = 0 { didSet { retweetsCountLabel.attributedText = NSAttributedString.retweetsCountAttributes(with: retweetsCount) } } var repliesCount: Int = 0 { didSet { repliesCountLabel.attributedText = NSAttributedString.repliesCountAttributes(with: repliesCount) } } func configure(_ user: User, coordinator: UserDetailCoordinator) { backgroundColor = .backgroundBlue() // descriptionLabel.text = user.userDescription // if let stringURL = user.profileImageURL { // profileImage.af_setImage(withURL: URL(string: stringURL)!, placeholderImage: UIImage(asset: .placeholder)) // } // totalTweetsCount = user.tweetsCount() // retweetsCount = user.retweetedTweetsCount() // repliesCount = user.repliesTweetsCount() // tweetsCount = totalTweetsCount - retweetsCount - repliesCount self.coordinator = coordinator // Set up Tweet label // descriptionLabel.configureBio(URLHandler: { // self.coordinator.presentSafari($0) // }, hashtagHandler: { // self.coordinator.open(hashtag: $0) // }, mentionHandler: { // self.coordinator.open(user: $0) // }) } }
mit
a17e5a072322e4adb9cf68f64ab349cc
31.450704
120
0.670573
4.89172
false
false
false
false
artursDerkintis/YouTube
YouTube/ChannelProvider.swift
1
4842
// // ChannelProvider.swift // YouTube // // Created by Arturs Derkintis on 1/28/16. // Copyright © 2016 Starfly. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class ChannelProvider: NSObject { func getVideosOfChannel(channelId: String, accessToken : String?, pageToken : String?, completion: (nextPageToken: String?, items : [Item]) -> Void){ let url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=\(channelId)&key=\(kYoutubeKey)&order=date&type=video" var params = Dictionary<String, AnyObject>() params["maxResults"] = 30 if let pageToken = pageToken{ params["pageToken"] = pageToken } if let token = accessToken{ params["access_token"] = token } let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!, parameters : params).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) //print("JSON: \(json)") if let array = json["items"].array{ self.parseItems(array, completion: { (items) -> Void in let nextpagetoken = json["nextPageToken"].string completion(nextPageToken: nextpagetoken, items: items) }) } } case .Failure(let error): print(error) } } } func parseItems(objects : [JSON], completion : (items : [Item]) -> Void){ var items = [Item]() for object in objects{ let item = Item() items.append(item) self.parseItem(object, item: item, completion: { (item) -> Void in let amount = items.filter({ (item) -> Bool in return item.type != .None }) if amount.count == objects.count{ completion(items: items) } }) } } func parseItem(object : JSON, item : Item, completion : (item : Item) -> Void){ if let kind = object["id"]["kind"].string{ switch kind{ case "youtube#video": let videoId = object["id"]["videoId"].string let video = Video() video.getVideoDetails(videoId!, completion: { (videoDetails) -> Void in video.videoDetails = videoDetails item.video = video completion(item: item) }) break default: item.type = .Unrecognized break } } } } func haveISubscribedToChannel(id: String, token : String, completion : (Bool) -> Void){ let url = "https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&mine=true&access_token=\(token)&forChannelId=\(id)" let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) if let array = json["items"].array{ print(array.count == 0 ? "empty" : "full") completion(array.count == 0 ? false : true) } } case .Failure(let error): print(error) } } } func getSubscritionId(channelId : String, token : String?, completion:(subscriptionId : String) -> Void){ let url = "https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&mine=true&access_token=\(token ?? "")&forChannelId=\(channelId)" let setCH = NSCharacterSet.URLQueryAllowedCharacterSet() Alamofire.request(.GET, url.stringByAddingPercentEncodingWithAllowedCharacters(setCH)!).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) print(json) if let array = json["items"].array{ if let id = array[0]["id"].string{ completion(subscriptionId: id) } } } break case .Failure(let error): print(error) break } } }
mit
7c8b9c470ff04cfc8cdf3d6364616c6f
36.246154
154
0.527784
5.053236
false
false
false
false
dreamsxin/swift
test/1_stdlib/UIKit.swift
3
2762
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: OS=ios import UIKit import StdlibUnittest let UIKitTests = TestSuite("UIKit") private func printDevice(_ o: UIDeviceOrientation) -> String { var s = "\(o.isPortrait) \(UIDeviceOrientationIsPortrait(o)), " s += "\(o.isLandscape) \(UIDeviceOrientationIsLandscape(o)), " s += "\(o.isFlat), \(o.isValidInterfaceOrientation) " s += "\(UIDeviceOrientationIsValidInterfaceOrientation(o))" return s } private func printInterface(_ o: UIInterfaceOrientation) -> String { return "\(o.isPortrait) \(UIInterfaceOrientationIsPortrait(o)), " + "\(o.isLandscape) \(UIInterfaceOrientationIsLandscape(o))" } UIKitTests.test("UIDeviceOrientation") { expectEqual("false false, false false, false, false false", printDevice(.unknown)) expectEqual("true true, false false, false, true true", printDevice(.portrait)) expectEqual("true true, false false, false, true true", printDevice(.portraitUpsideDown)) expectEqual("false false, true true, false, true true", printDevice(.landscapeLeft)) expectEqual("false false, true true, false, true true", printDevice(.landscapeRight)) expectEqual("false false, false false, true, false false", printDevice(.faceUp)) expectEqual("false false, false false, true, false false", printDevice(.faceDown)) } UIKitTests.test("UIInterfaceOrientation") { expectEqual("false false, false false", printInterface(.unknown)) expectEqual("true true, false false", printInterface(.portrait)) expectEqual("true true, false false", printInterface(.portraitUpsideDown)) expectEqual("false false, true true", printInterface(.landscapeLeft)) expectEqual("false false, true true", printInterface(.landscapeRight)) } UIKitTests.test("UIEdgeInsets") { let insets = [ UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.0, right: 4.0), UIEdgeInsets(top: 1.0, left: 2.0, bottom: 3.1, right: 4.0), UIEdgeInsets.zero ] checkEquatable(insets, oracle: { $0 == $1 }) } UIKitTests.test("UIOffset") { let offsets = [ UIOffset(horizontal: 1.0, vertical: 2.0), UIOffset(horizontal: 1.0, vertical: 3.0), UIOffset.zero ] checkEquatable(offsets, oracle: { $0 == $1 }) } class TestChildView : UIView, CustomPlaygroundQuickLookable { convenience init() { self.init(frame: CGRect(x: 0, y: 0, width: 10, height: 10)) } var customPlaygroundQuickLook: PlaygroundQuickLook { return .text("child") } } UIKitTests.test("CustomPlaygroundQuickLookable") { switch PlaygroundQuickLook(reflecting: TestChildView()) { case .text("child"): break default: expectUnreachable( "TestChildView custom quicklookable should have been invoked") } } runAllTests()
apache-2.0
43adddcd4526737d253b9a308b71c905
27.183673
69
0.705286
4.268934
false
true
false
false
ilyathewhite/Euler
EulerSketch/EulerSketch/SketchCore.swift
1
23262
// // SketchCore.swift // // Created by Ilya Belenkiy on 7/25/16. // Copyright © 2016 Ilya Belenkiy. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif public typealias ViewPoint = CGPoint /// Possible errors when running sketch commands public enum SketchError: Error, CustomStringConvertible { /// Couldn't find the style with a given name. case styleNotFound(name: String) /// Couldn't find a figure with a given name (for example, triangle ABC) case figureNotFound(name: String, kind: FigureKind) /// Couldn't find a figure with a given full name (for example, line_AB) case figureFullNameNotFound(fullName: String) /// Tried to add the same figure twice. case figureAlreadyAdded(name: String, kind: FigureKind) /// Failed to create a figure. This can happen if the evaluation function /// fails to compute a value from other figures in the sketch. For example, /// if a figure is the intersection of 2 lines, and the 2 lines are parallel. case figureNotCreated(name: String, kind: FigureKind) /// The name fails to satisfy the common geometric conventions. For example, /// triangles are expected to be named by their 3 vertices. case invalidFigureName(name: String, kind: FigureKind) /// 2 rays that are expected to have the same vertex have different vertices. case invalidCommonVertex(ray1: String, ray2: String) /// Every kind of figure has its own prefix (for example, "line_"). The error /// means that the prefix couldn't be found. case invalidFigureNamePrefix(prefix: String) case invalidValue(argName: String) /// The context expected a different kind of figure. For example, /// if a command expected a triangle but got circle. case unexpectedFigureNamePrefix(prefix: String, expected: String) public var description: String { switch self { case let .styleNotFound(styleName): return "Style \(styleName) not found." case let .figureNotFound(name, kind): return "\(kind.rawValue) \(name) not found." case let .figureFullNameNotFound(fullName): return "\(fullName) not found" case let .figureAlreadyAdded(name, kind): return "\(kind.rawValue) \(name) already added." case let .figureNotCreated(name, kind): return "\(kind.rawValue) \(name) not created." case let .invalidFigureName(name, kind): return "\(kind.rawValue) name \(name) is invalid." case let .invalidFigureNamePrefix(prefix): return "Figure name prefix \(prefix) is invalid." case let .invalidValue(argName): return "Invalid value for argument \(argName)" case let .unexpectedFigureNamePrefix(prefix, expected): return "Expected figure name prefix \(expected), got \(prefix)." case let .invalidCommonVertex(ray1, ray2): return "Expected rays \(ray1) and \(ray2) to have the same vertex." } } } /// The model of a complete geometric sketch. open class Sketch { /// An assertion about the figures in the sketch struct Assertion { /// The message to print if the assertion fails let message: String /// The condition that must be true for any valid configuration of the sketch let assertion: () throws -> Bool func eval() throws { if try !assertion() { print("Assertion failed:\n\(message)\n") } } } /// The origin of the model coordinate system in View coordinates. var origin: HSPoint = HSPoint(0, 0) /// All the figures in the sketch, in the order that they were added. fileprivate var figures: [FigureType] = [] /// The figure lookup table. The key is the complete figure name, /// includig the figure prefix. fileprivate var figureDict = [String: FigureType]() /// The constructor that creates an empty sketch. public init() {} /// Assertions about the figures in the sketch private var assertions: [Assertion] = [] /// Adds an assertion that evaluates after the sketch evaluation if the evaluation succeeds. /// This means that assertions are evaluated whenever the sketch changes. public func assert(_ message: String, assertion: @escaping () throws -> Bool) { assertions.append(Assertion(message: message, assertion: assertion)) } // MARK: Origin and Scale /// Converts point `viewPoint` from view to sketch coordinates. func sketchPointFromViewPoint(_ viewPoint: ViewPoint) -> HSPoint { return HSPoint(Double(viewPoint.x) - origin.x, Double(viewPoint.y) - origin.y) } /// Converts `point` from sketch to view coordinates. func viewPointFromSketchPoint(_ point: Point) -> (Double, Double) { return (origin.x + point.x, origin.y + point.y) } /// Drags figure named `figureName` from point `(fromX, fromY)` to point `(toX, toY)`. /// Both points are in the view coordinates. /// If `figureName` is nil, drags the sketch origin. /// /// This is an overload that translates view coordinates to sketch coordinates. See other /// functions for details. open func drag(_ figureName: String?, fromViewPoint fromPoint: ViewPoint, toViewPoint toPoint: ViewPoint) { let dx = Double(toPoint.x - fromPoint.x), dy = Double(toPoint.y - fromPoint.y) if let figureName = figureName { let fromSketchPoint = sketchPointFromViewPoint(fromPoint) drag(figureName, from: fromSketchPoint, by: (dx, dy)) eval() } else { origin.update(x: origin.x + dx, y: origin.y + dy) } } /// Scales all the free points in the sketch by `factor`. open func scale(_ factor: Double) { for figure in figures { if let point = figure as? PointFigure , point.free { var pnt = point.value pnt?.update(x: point.x * factor, y: point.y * factor) point.value = pnt } } eval() } /// Translates all the free points in the sketch by `(dx, dy)`. open func translate(by vector: Vector) { for figure in figures { if let point = figure as? PointFigure , point.free { var pnt = point.value pnt?.update(x: point.x + vector.dx, y: point.y + vector.dy) point.value = pnt } } eval() } // MARK: Find Figure /// Finds the figure with `name` by forming the full name with `prefix`. func findFigure(name: String, prefix: FigureNamePrefix) -> FigureType? { return figureDict[prefix.fullName(name)] } /// Finds the figure with a given full name. func findFigure(fullName name: String) -> FigureType? { return figureDict[name] } /// Returns the figure named `name` of a given type. The figure /// is expected to exist so the method throws an error if the figure is not found. /// /// The full name for the figure is formed from its name and type. func getFigure<T>(name: String) throws -> T where T: FigureType { if T.self == RayFigure.self { addRayIfNeeded(name) } else if T.self == LineFigure.self { addLineIfNeeded(name) } else if T.self == SegmentFigure.self { addSegmentIfNeeded(name) } let prefix = T.namePrefix() guard let res = findFigure(name: name, prefix: prefix) as? T else { throw SketchError.figureNotFound(name: name, kind: prefix.figureKind!) } return res } /// A wrapper for getFigure() to get the basic values for assertions func getFigureValue<T>(name: String) throws -> T where T: Shape { let figure: Figure<T> = try getFigure(name: name) return figure.value } /// The same wrapper as the generic function. It has a separate definition /// because otherwise missing lines may not be automatically added to the sketch. /// (This may happen because lines can be of different types, not just Figure<HSLine>.) func getFigureValue(name: String) throws -> HSLine { addLineIfNeeded(name) let figure: Figure<HSLine> = try getFigure(name: name) return figure.value } /// Adds `figure` to the lookup table. fileprivate func addToFigureDict(_ figure: FigureType) throws { guard figureDict[figure.fullName] == nil else { throw SketchError.figureAlreadyAdded(name: figure.fullName, kind: figure.fullNamePrefix.figureKind!) } figureDict[figure.fullName] = figure } /// Removes all figures starting from `index`. This method is useful when /// the user tries to add a complex figure that is constructed from smaller /// figures, and addition of the complex figure fails for some reason. /// In that case, this method can be used to rollback to a previous state. fileprivate func removeFigures(startIndex index: Int) { guard index < figures.count else { return } let range = index..<figures.count let removedFigures = figures[range] for figure in removedFigures { figureDict.removeValue(forKey: figure.fullName) } for figure in figures[0..<index] { removedFigures.forEach { figure.removeDependentFigure($0) } } figures.removeSubrange(range) } // MARK: Dragging func dragEndMessage(figureFullName: String) -> String? { guard let figure = findFigure(fullName: figureFullName) else { return nil } return figure.dragEndMessage } /// Returns the closest draggable figure and its closest point from `point` at a distance no larger than `minDistance`. /// All points are in the sketch coordinates. func closestDraggableFigureFromPoint(_ point: Point, minDistance: Double) -> (FigureType?, Point?) { var candidates = Array(figureDict.values.filter { (figure: FigureType) in if !figure.draggable { return false } let (dist, _) = figure.distanceFromPoint(point) return dist < minDistance }) if candidates.count == 0 { return (nil, nil) } else if candidates.count == 1 { let figure = candidates[0] let (_, closestPoint) = figure.distanceFromPoint(point) return (figure, closestPoint) } else { // closest point let pointFigures = candidates.filter { $0 is PointFigure } if pointFigures.count > 0 { typealias T = (pointFigure: PointFigure?, closestPoint: Point?, distance: Double) let initial: T = (nil, nil, 0) let res = pointFigures.reduce(initial, { (val: T, figure: FigureType) -> T in let pointFigure = figure as! PointFigure let (distance, closestPoint) = pointFigure.distanceFromPoint(point) return (val.pointFigure == nil) || (distance < val.distance) ? (pointFigure, closestPoint, distance) : val }) return (res.pointFigure, res.closestPoint) } // closest figure typealias T = (figure: FigureType?, closestPoint: Point?, distance: Double) let initial: T = (nil, nil, 0) let res = candidates.reduce(initial, { (val: T, figure: FigureType) -> T in let (distance, closestPoint) = figure.distanceFromPoint(point) return (val.figure == nil) || (distance < val.distance) ? (figure, closestPoint, distance) : val }) return (res.figure, res.closestPoint) } } /// Returns the closest draggable figure and its closest point from `point` at a distance no larger than `minDistance`. /// All points are in the view coordinates. open func closestDraggableFigureFromViewPoint(_ viewPoint: ViewPoint, minDistance: CGFloat) -> (String?, ViewPoint?) { let sketchPoint = sketchPointFromViewPoint(viewPoint) let (figure, closestSketchPoint) = closestDraggableFigureFromPoint(sketchPoint, minDistance: Double(minDistance)) if let figure = figure, let closestSketchPoint = closestSketchPoint { let (x, y) = viewPointFromSketchPoint(closestSketchPoint) return (figure.fullName, ViewPoint(x: x, y: y)) } else { return (nil, nil) } } /// Drags the figure with a given name from `point` moving some part of it /// (or by translating if it's free to move) by `vector`. Also updates /// all other figures already in the sketch as needed. func drag(_ name: String, from point: HSPoint, by vector: Vector) { guard let figure = findFigure(name: name, prefix: .None) else { assertionFailure("Figure \(name) not found.") return } figure.applyUpdateFunc(from: point, by: vector) } // MARK: Add Figure /// Adds `figure` with a given `style` for drawing. @discardableResult func addFigure(_ figure: FigureType, style: DrawingStyle?) throws -> FigureSummary { try addToFigureDict(figure) if !(figure is PointFigure) { figure.drawingStyle = style } figures.append(figure) // must be the last step to make sure that all dependencies are added last figure.sketch = self return figure.summary } /// Whether the sketch already contains a figure with the given name. func containsFigure(kind: FigureKind, name: String) -> Bool { return figureDict[kind.fullName(name)] != nil } /// Adds `figure` as an additional construction. Can be used directly or for implicitly created figures. @discardableResult func addExtraFigure(_ figure: FigureType, style: DrawingStyle? = .extra) throws -> FigureSummary { return try addFigure(figure, style: style) } // MARK: Eval /// Whether the sketch needs to go back to its previos state. This can happen if /// a figure cannot be constructed, for example, if there is a point specified as /// the intersection of 2 figures, and those 2 figures don't intersect. fileprivate var shouldRollback = false /// Sets the flag that the sketch needs to go back to its preious state. func setNeedsRollback() { shouldRollback = true } /// Evaluates all figures in the order that they were added and either changes /// all the figures to the new state or returns the sketch to its previous good state. open func eval() { // debugPrint("-------------------------") for figure in figures { // debugPrint(figure.fullName) figure.eval() if shouldRollback { break } } let finishEval: (_ figure: FigureType) -> () = shouldRollback ? { $0.rollback() } : { $0.commit() } for figure in figures { finishEval(figure) } if !shouldRollback { do { try assertions.forEach { try $0.eval() } } catch { print(error) } } shouldRollback = false } // draw /// Draws all figures via `renderer`. func draw(_ renderer: Renderer) { var points: [PointFigure] = [] for figure in figures where !figure.hidden { if (figure is PointFigure) { points.append(figure as! PointFigure) } else { figure.draw(renderer) } } // points should be drawn last for style // draw regular points last to cover any extra drawing for special point types for point in points where !point.kind.isRegular { point.draw(renderer) } for point in points where point.kind.isRegular { point.draw(renderer) } } /// Draws all figures to a given graphics context. open func draw(_ context: CGContext) { let renderer = CGRenderer(context: context) draw(renderer) } // MARK: Top Level Helper Functions /// The content for `FigureResult`. Useful for displaying the result and quick look in playgrounds. public struct FigureSummary: CustomStringConvertible, CustomPlaygroundDisplayConvertible { /// The figure string summary. let string: String /// The sketch (useful for quick look). public let sketch: Sketch // CustomStringConvertible public var description: String { return string } // CustomPlaygroundDisplayConvertible public var playgroundDescription: Any { return sketch.playgroundDescription } } /// The top level functions are really commands for adding figures. They are likely to be used /// in a playground while writing a script to create a sketch. In that context, using do / catch /// blocks and try statements is very verbouse. In playgrounds, `Result` shows errors on the side /// without convoluting the script. public typealias FigureResult = Result<FigureSummary> /// Hides the figure named `fullName`. open func hide(figureNamed fullName: String) { guard let figure = findFigure(fullName: fullName) else { return } figure.hidden = true } /// Returns the point names from `string`. `string` is expected to be a figure name that /// follows the universal geometric naming conventions (for example, triangle `ABC`). func scanPointNames(_ string: String, expected: FigureNamePrefix) throws -> [String] { func isUppercaseChar(_ idx: String.Index) -> Bool { return ("A"..."Z").contains(string[idx]) } var idx = string.startIndex while (idx != string.endIndex) && (string[idx] != FigureNamePrefix.lastChar) { idx = string.index(after: idx) } if (idx != string.endIndex) { idx = string.index(after: idx) } let prefix = (idx == string.endIndex) ? "" : String(string[..<idx]) guard let prefixVal = FigureNamePrefix(rawValue: prefix) , (prefixVal == .None) || (prefixVal == expected) else { throw SketchError.invalidFigureNamePrefix(prefix: prefix) } if idx == string.endIndex { idx = string.startIndex } guard idx != string.endIndex else { return [] } var names = [String]() var nameStartIdx = idx idx = string.index(after: nameStartIdx) while idx != string.endIndex { if isUppercaseChar(idx) { names.append(String(string[nameStartIdx..<idx])) nameStartIdx = idx } idx = string.index(after: idx) } if (nameStartIdx != string.endIndex) && isUppercaseChar(nameStartIdx) { names.append(String(string[nameStartIdx...])) } return names } /// Returns the point figures used in `figureName`. func findVertices(_ figureName: String, expected: FigureNamePrefix) throws -> [PointFigure] { let vertexNames = try scanPointNames(figureName, expected: expected) var res = [PointFigure]() res.reserveCapacity(vertexNames.count) for vertexName in vertexNames { res.append(try self.getFigure(name: vertexName)) } return res } } /// Extension for sketch assertions public extension Sketch { /// Returns the point value for the point with the given name. func getPoint(_ name: String) throws -> HSPoint { return try getFigureValue(name: name) } /// Returns the segment value for the segment with the given name. func getSegment(_ name: String) throws -> HSSegment { return try getFigureValue(name: name) } /// Returns the line value for the line with the given name. func getLine(_ name: String) throws -> HSLine { return try getFigureValue(name: name) } /// Returns the ray value for the ray with the given name. func getRay(_ name: String) throws -> HSRay { return try getFigureValue(name: name) } /// Returns the angle value for the angle with the given name. func getAngle(_ name: String) throws -> HSAngle { return try getFigureValue(name: name) } /// Returns the circle value for the circle with the given name. func getCircle(_ name: String) throws -> HSCircle { return try getFigureValue(name: name) } } /// Extension for sketch animations public extension Sketch { /// Maps a parameter in [0, 1] to a point on the plane typealias ParametricCurve = (Double) -> HSPoint /// Returns a parametric curve that moves a point through a segment path from the first point to the second point. static func makeSegmentParametricCurve(from p1: Point, to p2: Point) -> ParametricCurve? { guard let segment = HSSegment(vertex1: p1, vertex2: p2) else { return nil } let length = segment.length let ray = segment.ray return { param in ray.pointAtDistance(param * length) } } /// Returns a parametric curve that moves a point through the arc specified by the circle with a given center and radius, /// and the start and end angle (in degrees). static func makeArcParametricCurve(center: Point, radius: Double, fromAngle degAngle1: Double, toAngle degAngle2: Double) -> ParametricCurve { let angle1 = toRadians(degAngle1) let angle2 = toRadians(degAngle2) return { param in let angle = angle1 + (angle2 - angle1) * param let ray = HSRay(vertex: center, angle: angle) return ray.pointAtDistance(radius) } } /// Returns a parametric curve that moves a point through the curve path in the reverse direction of the input curve. static func makeReverseCurve(from curve: @escaping ParametricCurve) -> ParametricCurve { return { param in curve(max(0.0, 1.0 - param)) } } /// Combines 2 parametric curves into 1 by moving a point through the first path when the parameter is in [0, 0.5], /// and then through the second path when the parameter is in (0.5, 1]. static func combineCurves(curve1: @escaping ParametricCurve, curve2: @escaping ParametricCurve) -> ParametricCurve { return { param in (param <= 0.5) ? curve1(min(2.0 * param, 1.0)) : curve2(min(2.0 * (param - 0.5), 1.0)) } } /// Returns a parametric curve where the point moves through the input curve path forward during the first half, /// and then moves backward during the second half. // The implementation is a good example of how these APIs compose. static func makeLoopCurve(from curve: @escaping ParametricCurve) -> ParametricCurve { return combineCurves(curve1: curve, curve2: makeReverseCurve(from: curve)) } } /// Extension for quick look in playgrounds. extension Sketch: CustomPlaygroundDisplayConvertible { public func quickView() -> SketchView { let view = SketchView(frame: CGRect(origin: .zero, size: CGSize(width: 600, height: 600))) view.sketch = self return view } public var playgroundDescription: Any { return quickView() } } /// Extension for dislpaying a figure short summary (useful in playgrounds and debugger). extension FigureType { var summary: Sketch.FigureSummary { return Sketch.FigureSummary(string: summaryName, sketch: sketch!) } }
mit
1651317233d491239085f81b98844855
36.277244
145
0.643781
4.515822
false
false
false
false
VanHack/binners-project-ios
ios-binners-project/NSDate+Extension.swift
1
7920
// // NSDate+Extension.swift // ios-binners-project // // Created by Matheus Ruschel on 3/14/16. // Copyright © 2016 Rodrigo de Souza Reis. All rights reserved. import UIKit enum DateFormatType { case time, date } extension Date { static func currentHour() -> Int { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "HH:mm:ss" let dateNow = Date() let calendar = Calendar.current let comp = (calendar as NSCalendar).components([.hour], from: dateNow) return comp.hour! } func printDate() -> String { return "\(self.dayMonthYear().1)/\(self.dayMonthYear().0)/\(self.dayMonthYear().2)" } func formattedDate(_ dateType: DateFormatType) -> String { let formatter = DateFormatter() switch dateType { case .date: formatter.timeStyle = .none formatter.dateStyle = .short case .time: formatter.timeStyle = .short formatter.dateStyle = .none } return formatter.string(from: self) } func printTime() -> String { var timePeriod = "am" var minute: String = "\(self.getMinute())" var hour: String = "\(self.getHour())" print(hour) var hourValue: Int = self.getHour() if self.getHour() > 12 { timePeriod = "pm" hourValue = hourValue - 12 hour = "\(hourValue)" } if self.getMinute() < 10 { minute = "0\(self.getMinute())" } if hourValue < 10 { hour = "0\(hourValue)" } return "\(hour):\(minute) " + timePeriod } func dayMonthYear() -> ( Int, Int, Int ) { let calendar = Calendar.current let components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday], from: self) return ( components.day!, components.month!, components.year!) } func changeDay(_ day: Int) -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday], from: self) components.day = day let date = calendar.date(from: components) return date! } func getHour() -> Int { let calendar = Calendar.current let components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday, .hour, .minute], from: self) return components.hour! } func getMinute() -> Int { let calendar = Calendar.current let components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday, .hour, .minute], from: self) return components.minute! } func changeHour(_ hour: Int) -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday, .hour, .minute], from: self) components.hour = hour let date = calendar.date(from: components) return date! } func changeMinute(_ minute: Int) -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday, .hour, .minute], from: self) components.minute = minute let date = calendar.date(from: components) return date! } func dayOfTheWeek() -> Int { let calendar = Calendar.current let components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday], from: self) return components.weekday! } func daysOfTheMonth(_ date: Date) -> [(String, String, String, String)] { var dayStrings = [( String, String, String, String)]() var weekDay = date.getDateForFirstDayOfTheMonth().dayOfTheWeek() for index in 1...self.getDaysOfTheMonth().length { dayStrings.append( (String(index), String(weekDay), String(date.dayMonthYear().1), String(date.dayMonthYear().2) )) weekDay += 1 if weekDay > 7 { weekDay = 1 } } return dayStrings } func getDateForFirstDayOfTheMonth() -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday], from: self) components.day = 1 let date = calendar.date(from: components) return date! } func getPastMonth() -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday], from: self) components.month = components.month! - 1 let date = calendar.date(from: components) return date! } func getNextMonth() -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday], from: self) components.month = components.month! + 1 let date = calendar.date(from: components) return date! } func nextDayDate() -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday], from: self) components.day = components.day! + 1 let date = calendar.date(from: components) return date! } func previousDayDate() -> Date { let calendar = Calendar.current var components = (calendar as NSCalendar).components( [.year, .month, .day, .weekOfMonth, .weekday], from: self) components.day = components.day! - 1 let date = calendar.date(from: components) return date! } func getDaysOfTheMonth() -> NSRange { let calendar = Calendar.current let daysRange = (calendar as NSCalendar).range(of: .day, in: .month, for: self) return daysRange } static func parseDateFromServer(_ dateString:String) -> Date? { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.'000Z'" return dateFormatter.date(from: dateString) } func monthLiteral() -> String { let month = self.dayMonthYear().1 switch month { case 1: return "January" case 2: return "February" case 3: return "March" case 4: return "April" case 5: return "May" case 6: return "June" case 7: return "July" case 8: return "August" case 9: return "September" case 10: return "October" case 11: return "November" default: return "December" } } func dayOfWeekLiteral() -> String { let day = self.dayOfTheWeek() switch day { case 1: return "Sunday" case 2: return "Monday" case 3: return "Tuesday" case 4: return "Wednesday" case 5: return "Thursday" case 6: return "Friday" default: return "Saturday" } } }
mit
75d7ef7a76aee11940b53c917edeadb1
28.32963
91
0.532264
4.733413
false
false
false
false
josve05a/wikipedia-ios
WMF Framework/SummaryExtensions.swift
2
5824
extension WMFArticle { func merge(_ article: WMFArticle) { guard article.objectID != objectID else { return } // merge important keys not set by the summary let keysToMerge = [#keyPath(WMFArticle.savedDate), #keyPath(WMFArticle.placesSortOrder), #keyPath(WMFArticle.pageViews)] for key in keysToMerge { guard let valueToMerge = article.value(forKey: key) else { continue } // keep the later date when both have date values if let dateValueToMerge = valueToMerge as? Date, let dateValue = value(forKey: key) as? Date, dateValue > dateValueToMerge { continue } // prefer existing values if value(forKey: key) != nil { continue } setValue(valueToMerge, forKey: key) } if let articleReadingLists = article.readingLists { addReadingLists(articleReadingLists) } if let articlePreviewReadingLists = article.previewReadingLists { addPreviewReadingLists(articlePreviewReadingLists) } if article.isExcludedFromFeed { isExcludedFromFeed = true } let mergeViewedProperties: Bool if let viewedDateToMerge = article.viewedDate { if let existingViewedDate = viewedDate, existingViewedDate > viewedDateToMerge { mergeViewedProperties = false } else { mergeViewedProperties = true } } else { mergeViewedProperties = false } if mergeViewedProperties { viewedDate = article.viewedDate viewedFragment = article.viewedFragment viewedScrollPosition = article.viewedScrollPosition wasSignificantlyViewed = article.wasSignificantlyViewed } } @objc public func update(withSummary summary: ArticleSummary) { if let original = summary.original { imageURLString = original.source imageWidth = NSNumber(value: original.width) imageHeight = NSNumber(value: original.height) } else { imageURLString = nil imageWidth = NSNumber(value: 0) imageHeight = NSNumber(value: 0) } wikidataDescription = summary.articleDescription displayTitleHTML = summary.displayTitle ?? summary.title ?? "" snippet = summary.extract?.wmf_summaryFromText() if let summaryCoordinate = summary.coordinates { coordinate = CLLocationCoordinate2D(latitude: summaryCoordinate.lat, longitude: summaryCoordinate.lon) } else { coordinate = nil } } } extension NSManagedObjectContext { @objc public func wmf_createOrUpdateArticleSummmaries(withSummaryResponses summaryResponses: [String: ArticleSummary]) throws -> [String: WMFArticle] { guard !summaryResponses.isEmpty else { return [:] } var keys: [String] = [] var reverseRedirectedKeys: [String: String] = [:] keys.reserveCapacity(summaryResponses.count) for (key, summary) in summaryResponses { guard let summaryKey = summary.key, key != summaryKey // find the mismatched keys else { keys.append(key) continue } reverseRedirectedKeys[summaryKey] = key keys.append(summaryKey) do { let articlesWithKey = try fetchArticles(withKey: key) let articlesWithSummaryKey = try fetchArticles(withKey: summaryKey) guard let canonicalArticle = articlesWithSummaryKey.first ?? articlesWithKey.first else { continue } for article in articlesWithKey { canonicalArticle.merge(article) delete(article) } for article in articlesWithSummaryKey { canonicalArticle.merge(article) delete(article) } canonicalArticle.key = summaryKey } catch let error { DDLogError("Error fetching articles for merge: \(error)") } } var keysToCreate = Set(keys) let articlesToUpdateFetchRequest = WMFArticle.fetchRequest() articlesToUpdateFetchRequest.predicate = NSPredicate(format: "key IN %@", keys) var articles: [String: WMFArticle] = [:] articles.reserveCapacity(keys.count) let fetchedArticles = try self.fetch(articlesToUpdateFetchRequest) for articleToUpdate in fetchedArticles { guard let articleKey = articleToUpdate.key else { continue } let requestedKey = reverseRedirectedKeys[articleKey] ?? articleKey guard let result = summaryResponses[requestedKey] else { articles[requestedKey] = articleToUpdate continue } articleToUpdate.update(withSummary: result) articles[requestedKey] = articleToUpdate keysToCreate.remove(articleKey) } for key in keysToCreate { let requestedKey = reverseRedirectedKeys[key] ?? key guard let result = summaryResponses[requestedKey], // responses are by requested key let article = self.createArticle(withKey: key) else { // article should have redirected key continue } article.update(withSummary: result) articles[requestedKey] = article } try self.save() return articles } }
mit
54b329137369a9f83abe9646058f3a21
39.165517
155
0.586538
5.800797
false
false
false
false
wumbo/Wumbofant
Wumbofant/CSVLoader.swift
1
3651
// // CSVLoader.swift // Wumbofant // // Created by Simon Crequer on 13/07/15. // Copyright (c) 2015 Simon Crequer. All rights reserved. // import Cocoa import CoreData class CSVLoader { var url: NSURL init(url: NSURL) { self.url = url loadEntries() } lazy var entries: [LogEntry] = { let managedObjectContext = (NSApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext let fetchRequest = NSFetchRequest(entityName: "LogEntry") let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [LogEntry] return fetchResults }() /** Loads the CSV file given by url and parses it into an array of LogEntry objects */ func loadEntries() { var error: NSError? var contents: String? = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error) if error != nil { println("Error fetching file contents: \(error)") } else if contents != nil { var lines: [String] = contents!.componentsSeparatedByString("\r\n") if lines[0] == "Product,Project,Iteration,Story,Task,Comment,User,Date,Spent effort (hours)" { lines.removeAtIndex(0) for line in lines { let items = readLine(line) let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd.MM.yyyy HH:mm" let date: NSDate = dateFormatter.dateFromString(items[7])! // Create a CoreData entity for the LogEntry that can be referenced from // anywhere in the application let entry = NSEntityDescription.insertNewObjectForEntityForName("LogEntry", inManagedObjectContext: (NSApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext!) as! LogEntry entry.product = items[0] entry.project = items[1] entry.iteration = items[2] entry.story = items[3] entry.task = items[4] entry.comment = items[5] entry.user = items[6] entry.date = date entry.spentEffort = NSNumber(float: NSString(string: items[8]).floatValue) } } } } /** Parses a line from the CSV file into an array of Strings. Rather than treating every comma as a seperator, it first checks if a comma is inside "quotation marks" and only treats it as a seperator if it isn't. :param: line The line of CSV data to be parsed :returns: An array of 9 Strings containing each part of the LogEntry */ private func readLine(line: String) -> [String] { var values: [String] = ["","","","","","","","",""] var index: Int = 0 var quoteReached: Bool = false for c in line { if c != "," && c != "\"" { values[index].append(c) } else if c == "\"" { if !quoteReached { quoteReached = true } else { quoteReached = false } } else if c == "," { if quoteReached { values[index].append(c) } else { index++ } } } return values } }
bsd-3-clause
504b7655f7a0b2a321b49325fba4a680
33.45283
216
0.523692
5.208274
false
false
false
false
breadwallet/breadwallet-core
Swift/BRCrypto/BRCryptoPayment.swift
1
15235
// // BRCryptoPayment.swift // BRCrypto // // Created by Michael Carrara on 8/27/19. // Copyright © 2019 Breadwallet AG. All rights reserved. // // See the LICENSE file at the project root for license information. // See the CONTRIBUTORS file at the project root for a list of contributors. // import Foundation import BRCryptoC public enum PaymentProtocolError: Error { case certificateMissing case certificateNotTrusted case signatureTypeUnsupported case signatureVerificationFailed case requestExpired internal init? (_ core: BRCryptoPaymentProtocolError) { switch core { case CRYPTO_PAYMENT_PROTOCOL_ERROR_NONE: return nil case CRYPTO_PAYMENT_PROTOCOL_ERROR_CERT_MISSING: self = .certificateMissing case CRYPTO_PAYMENT_PROTOCOL_ERROR_CERT_NOT_TRUSTED: self = .certificateNotTrusted case CRYPTO_PAYMENT_PROTOCOL_ERROR_SIGNATURE_TYPE_NOT_SUPPORTED: self = .signatureTypeUnsupported case CRYPTO_PAYMENT_PROTOCOL_ERROR_SIGNATURE_VERIFICATION_FAILED: self = .signatureVerificationFailed case CRYPTO_PAYMENT_PROTOCOL_ERROR_EXPIRED: self = .requestExpired default: self = .signatureVerificationFailed; preconditionFailure() } } } public enum PaymentProtocolRequestType { case bip70 case bitPay fileprivate init (_ core: BRCryptoPaymentProtocolType) { switch core { case CRYPTO_PAYMENT_PROTOCOL_TYPE_BIP70: self = .bip70 case CRYPTO_PAYMENT_PROTOCOL_TYPE_BITPAY: self = .bitPay default: self = .bip70; preconditionFailure() } } } public final class PaymentProtocolRequest { public static func create(wallet: Wallet, forBitPay json: Data) -> PaymentProtocolRequest? { guard CRYPTO_TRUE == cryptoPaymentProtocolRequestValidateSupported (CRYPTO_PAYMENT_PROTOCOL_TYPE_BITPAY, wallet.manager.network.core, wallet.currency.core, wallet.core) else { return nil } let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" let decoder = JSONDecoder() decoder.dateDecodingStrategy = .formatted(formatter) guard let req = try? decoder.decode(BitPayRequest.self, from: json) else { return nil } guard let builder = cryptoPaymentProtocolRequestBitPayBuilderCreate (wallet.manager.network.core, wallet.currency.core, PaymentProtocolRequest.bitPayAndBip70Callbacks, req.network, UInt64(req.time.timeIntervalSince1970), UInt64(req.expires.timeIntervalSince1970), req.requiredFeeRate, req.memo, req.paymentUrl.absoluteString, nil, 0) else { return nil } defer { cryptoPaymentProtocolRequestBitPayBuilderGive (builder) } for output in req.outputs { cryptoPaymentProtocolRequestBitPayBuilderAddOutput (builder, output.address, output.amount) } return cryptoPaymentProtocolRequestBitPayBuilderBuild (builder) .map { PaymentProtocolRequest(core: $0, wallet: wallet) } } public static func create(wallet: Wallet, forBip70 serialization: Data) -> PaymentProtocolRequest? { guard CRYPTO_TRUE == cryptoPaymentProtocolRequestValidateSupported (CRYPTO_PAYMENT_PROTOCOL_TYPE_BIP70, wallet.manager.network.core, wallet.currency.core, wallet.core) else { return nil } var bytes = [UInt8](serialization) return cryptoPaymentProtocolRequestCreateForBip70 (wallet.manager.network.core, wallet.currency.core, PaymentProtocolRequest.bitPayAndBip70Callbacks, &bytes, bytes.count) .map { PaymentProtocolRequest(core: $0, wallet: wallet) } } public var type: PaymentProtocolRequestType { return PaymentProtocolRequestType(cryptoPaymentProtocolRequestGetType (core)) } public var isSecure: Bool { return CRYPTO_TRUE == cryptoPaymentProtocolRequestIsSecure (core) } public var memo: String? { return cryptoPaymentProtocolRequestGetMemo (core) .map { asUTF8String($0) } } public var paymentURL: String? { return cryptoPaymentProtocolRequestGetPaymentURL (core) .map { asUTF8String($0) } } public var totalAmount: Amount? { return cryptoPaymentProtocolRequestGetTotalAmount (core) .map { Amount (core: $0, take: false) } } public var primaryTarget: Address? { return cryptoPaymentProtocolRequestGetPrimaryTargetAddress (core) .map { Address (core: $0, take: false) } } public private(set) lazy var commonName: String? = { return cryptoPaymentProtocolRequestGetCommonName(core) .map { asUTF8String ($0, true) } }() private lazy var error: PaymentProtocolError? = { return PaymentProtocolError(cryptoPaymentProtocolRequestIsValid(core)) }() public var requiredNetworkFee: NetworkFee? { return cryptoPaymentProtocolRequestGetRequiredNetworkFee (core) .map { NetworkFee (core: $0, take: false) } } internal let core: BRCryptoPaymentProtocolRequest private let manager: WalletManager private let wallet: Wallet private init(core: BRCryptoPaymentProtocolRequest, wallet: Wallet) { self.core = core self.manager = wallet.manager self.wallet = wallet } public func isValid() -> PaymentProtocolError? { return self.error } public func estimateFee(fee: NetworkFee, completion: @escaping (Result<TransferFeeBasis, Wallet.FeeEstimationError>) -> Void) { wallet.estimateFee(request: self, fee: fee, completion: completion) } public func createTransfer(estimatedFeeBasis: TransferFeeBasis) -> Transfer? { return wallet.createTransfer(request: self, estimatedFeeBasis: estimatedFeeBasis) } public func signTransfer(transfer: Transfer, paperKey: String) -> Bool { return manager.sign(transfer: transfer, paperKey: paperKey) } public func submitTransfer(transfer: Transfer) { manager.submit(transfer: transfer) } public func createPayment(transfer: Transfer) -> PaymentProtocolPayment? { return PaymentProtocolPayment.create(request: self, transfer: transfer, refund: wallet.target) } deinit { cryptoPaymentProtocolRequestGive (core) } fileprivate static let bitPayAndBip70Callbacks: BRCryptoPayProtReqBitPayAndBip70Callbacks = BRCryptoPayProtReqBitPayAndBip70Callbacks ( context: nil, validator: { (req, ctx, pkiType, expires, certBytes, certLengths, certsSz, digest, digestLen, signature, signatureLen) in let pkiType = asUTF8String (pkiType!) if pkiType != "none" { var certs = [SecCertificate]() let policies = [SecPolicy](repeating: SecPolicyCreateBasicX509(), count: 1) var trust: SecTrust? var trustResult = SecTrustResultType.invalid var certArray = [Data]() for index in 0..<certsSz { certArray.append(Data (bytes: certBytes![index]!, count: certLengths![index])) } for c in certArray { if let cert = SecCertificateCreateWithData(nil, c as CFData) { certs.append(cert) } } SecTrustCreateWithCertificates(certs as CFTypeRef, policies as CFTypeRef, &trust) if let trust = trust { SecTrustEvaluate(trust, &trustResult) } // verify certificate chain // .unspecified indicates a positive result that wasn't decided by the user guard trustResult == .unspecified || trustResult == .proceed else { return certs.isEmpty ? CRYPTO_PAYMENT_PROTOCOL_ERROR_CERT_MISSING : CRYPTO_PAYMENT_PROTOCOL_ERROR_CERT_NOT_TRUSTED } var status = errSecUnimplemented var pubKey: SecKey? if let trust = trust { pubKey = SecTrustCopyPublicKey(trust) } if let pubKey = pubKey, let digest = digest, let signature = signature { if pkiType == "x509+sha256" { status = SecKeyRawVerify(pubKey, .PKCS1SHA256, digest, digestLen, signature, signatureLen) } else if pkiType == "x509+sha1" { status = SecKeyRawVerify(pubKey, .PKCS1SHA1, digest, digestLen, signature, signatureLen) } } guard status == errSecSuccess else { if status == errSecUnimplemented { return CRYPTO_PAYMENT_PROTOCOL_ERROR_SIGNATURE_TYPE_NOT_SUPPORTED } else { return CRYPTO_PAYMENT_PROTOCOL_ERROR_SIGNATURE_VERIFICATION_FAILED } } } guard expires == 0 || NSDate.timeIntervalSinceReferenceDate <= Double(expires) else { return CRYPTO_PAYMENT_PROTOCOL_ERROR_EXPIRED } return CRYPTO_PAYMENT_PROTOCOL_ERROR_NONE }, nameExtractor: { (req, ctx, pkiType, certBytes, certLengths, certsSz) in var name: String? = nil var certArray = [Data]() for index in 0..<certsSz { certArray.append(Data (bytes: certBytes![index]!, count: certLengths![index])) } let pkiType = asUTF8String (pkiType!) if pkiType != "none" { for c in certArray { if let cert = SecCertificateCreateWithData(nil, c as CFData) { name = SecCertificateCopySubjectSummary(cert) as String? break } } } else if 0 != certsSz { // non-standard extention to include an un-certified request name name = String(data: certArray[0], encoding: .utf8) } return name.map { strdup ($0) } } ) } public final class PaymentProtocolPayment { fileprivate static func create(request: PaymentProtocolRequest, transfer: Transfer, refund: Address) -> PaymentProtocolPayment? { return cryptoPaymentProtocolPaymentCreate (request.core, transfer.core, refund.core) .map { PaymentProtocolPayment (core: $0) } } private let core: BRCryptoPaymentProtocolPayment private init (core: BRCryptoPaymentProtocolPayment) { self.core = core } public func encode() -> Data? { var bytesCount: Int = 0 if let bytes = cryptoPaymentProtocolPaymentEncode (core, &bytesCount) { defer { free (bytes) } return Data (bytes: bytes, count: bytesCount) } return nil } deinit { cryptoPaymentProtocolPaymentGive(core) } } public final class PaymentProtocolPaymentACK { public static func create(forBitPay json: Data) -> PaymentProtocolPaymentACK? { guard let ack = try? JSONDecoder().decode(BitPayAck.self, from: json) else { return nil } return PaymentProtocolPaymentACK (bitPayAck: ack) } public static func create(forBip70 serialization: Data) -> PaymentProtocolPaymentACK? { var bytes = [UInt8](serialization) return cryptoPaymentProtocolPaymentACKCreateForBip70 (&bytes, bytes.count) .map { PaymentProtocolPaymentACK (core: $0) } } private let impl: Impl private init(core: BRCryptoPaymentProtocolPaymentACK){ self.impl = .core(core) } private init(bitPayAck: BitPayAck){ self.impl = .bitPay(bitPayAck) } public var memo: String? { return impl.memo } private enum Impl { case core (BRCryptoPaymentProtocolPaymentACK) case bitPay (BitPayAck) fileprivate var memo: String? { switch self { case .core (let core): return cryptoPaymentProtocolPaymentACKGetMemo (core) .map { asUTF8String ($0) } case .bitPay (let ack): return ack.memo } } fileprivate func give() { switch self { case .core (let core): cryptoPaymentProtocolPaymentACKGive (core) case .bitPay: break } } } deinit { impl.give() } } fileprivate struct BitPayRequest: Decodable { fileprivate struct Output: Decodable { let amount: UInt64 let address: String } let network: String let currency: String let requiredFeeRate: Double let outputs: [Output] let time: Date let expires: Date let memo: String let paymentUrl: URL let paymentId: String } fileprivate struct BitPayPayment: Decodable { let currency: String let transactions: [String] } fileprivate struct BitPayAck: Decodable { let payment: BitPayPayment let memo: String? }
mit
7c80a0f5587a7f43de4ca7d075cdc1cc
38.879581
139
0.545162
5.740015
false
false
false
false
MaddTheSane/SwiftXPC
SwiftXPC/Transport/Connection.swift
1
3277
// // Connection.swift // DOS Prompt // // Created by William Kent on 7/28/14. // Copyright (c) 2014 William Kent. All rights reserved. // import Foundation import Dispatch import XPC public final class XPCConnection : XPCObject { public class func createAnonymousConnection() -> XPCConnection { return XPCConnection(anonymous: ()) } public convenience init(name: String, queue: dispatch_queue_t? = nil) { self.init(nativePointer: xpc_connection_create(name, queue)) } public convenience init(anonymous: ()) { self.init(nativePointer: xpc_connection_create(nil, nil)) } public convenience init(endpoint: XPCEndpoint) { self.init(nativePointer: xpc_connection_create_from_endpoint(endpoint.objectPointer)) } public func setTargetQueue(queue: dispatch_queue_t?) { xpc_connection_set_target_queue(objectPointer, queue) } public func setHandler(block: (XPCObject) -> ()) { xpc_connection_set_event_handler(objectPointer) { ptr in block(nativeTypeForXPCObject(ptr)) } } public func suspend() { xpc_connection_suspend(objectPointer) } public func resume() { xpc_connection_resume(objectPointer) } public func sendMessage(message: XPCDictionary) { xpc_connection_send_message(objectPointer, message.objectPointer) } public func sendMessage(message: XPCDictionary, replyHandler: (XPCObject) -> ()) { xpc_connection_send_message_with_reply(objectPointer, message.objectPointer, nil) { obj in replyHandler(nativeTypeForXPCObject(obj)) } } public func sendBarrier(barrier: () -> ()) { xpc_connection_send_barrier(objectPointer) { barrier() } } public func cancel() { xpc_connection_cancel(objectPointer) } // MARK: Properties public var name: String? { let ptr = xpc_connection_get_name(objectPointer) if ptr != nil { return String.fromCString(ptr) } else { return nil } } public var effectiveUserIDOfRemotePeer : uid_t { return xpc_connection_get_euid(objectPointer) } public var effectiveGroupIDOfRemotePeer : gid_t { return xpc_connection_get_egid(objectPointer) } public var processIDOfRemotePeer : pid_t { return xpc_connection_get_pid(objectPointer) } public var auditSessionIDOfRemotePeer : au_asid_t { return xpc_connection_get_asid(objectPointer) } } extension XPCDictionary { public var remoteConnection: XPCConnection { return XPCConnection(nativePointer: xpc_dictionary_get_remote_connection(objectPointer)) } /// Note: Due to the underlying implementation, this method will only work once. /// Subsequent calls will return nil. In addition, if the receiver does not have /// a reply context, this method will always return nil. public func createReply() -> XPCDictionary? { let ptr = xpc_dictionary_create_reply(objectPointer) if ptr == nil { return nil } return XPCDictionary(nativePointer: ptr) } }
mit
e29b3ce123ef1d0f029a18e17d95c90b
28.258929
96
0.638389
4.602528
false
false
false
false
mentrena/SyncKit
SyncKit/Classes/CoreData/CoreDataAdapter+Notifications.swift
1
5591
// // CoreDataAdapter+Notifications.swift // SyncKit // // Created by Manuel Entrena on 06/06/2019. // Copyright © 2019 Manuel Entrena. All rights reserved. // import Foundation import CoreData extension CoreDataAdapter { @objc func targetContextWillSave(notification: Notification) { if let object = notification.object as? NSManagedObjectContext, object == targetContext && !isMergingImportedChanges { let updated = Array(targetContext.updatedObjects) var identifiersAndChanges = [PrimaryKeyValue: [String]]() for object in updated { var changedValueKeys = [String]() for key in object.changedValues().keys { let relationship = object.entity.relationshipsByName[key] if object.entity.attributesByName[key] != nil || (relationship != nil && relationship!.isToMany == false) { changedValueKeys.append(key) } } if let identifier = uniqueIdentifier(for: object), changedValueKeys.count > 0 { identifiersAndChanges[identifier] = changedValueKeys } } let deletedIDs: [PrimaryKeyValue] = targetContext.deletedObjects.compactMap { if self.uniqueIdentifier(for: $0) == nil, let entityName = $0.entity.name { // Properties become nil when objects are deleted as a result of using an undo manager // Here we can retrieve their last known identifier and mark the corresponding synced // entity for deletion let identifierFieldName = self.identifierFieldName(forEntity: entityName) let committedValues = $0.committedValues(forKeys: [identifierFieldName]) guard let value = committedValues[identifierFieldName] else { return nil } return PrimaryKeyValue(value: value) } else { return uniqueIdentifier(for: $0) } } privateContext.perform { for (identifier, objectChangedKeys) in identifiersAndChanges { guard let entity = self.syncedEntity(withOriginIdentifier: identifier) else { continue } var changedKeys = Set<String>(entity.changedKeysArray) for key in objectChangedKeys { changedKeys.insert(key) } entity.changedKeysArray = Array(changedKeys) if entity.entityState == .synced && !entity.changedKeysArray.isEmpty { entity.entityState = .changed } entity.updatedDate = NSDate() } deletedIDs.forEach { (identifier) in guard let entity = self.syncedEntity(withOriginIdentifier: identifier) else { return } entity.entityState = .deleted entity.updatedDate = NSDate() } debugPrint("QSCloudKitSynchronizer >> Will Save >> Tracking %ld updates", updated.count) debugPrint("QSCloudKitSynchronizer >> Will Save >> Tracking %ld deletions", deletedIDs.count) self.savePrivateContext() } } } @objc func targetContextDidSave(notification: Notification) { if let object = notification.object as? NSManagedObjectContext, object == targetContext && !isMergingImportedChanges { let inserted = notification.userInfo?[NSInsertedObjectsKey] as? Set<NSManagedObject> let updated = notification.userInfo?[NSUpdatedObjectsKey] as? Set<NSManagedObject> let deleted = notification.userInfo?[NSDeletedObjectsKey] as? Set<NSManagedObject> var insertedIdentifiersAndEntityNames = [PrimaryKeyValue: String]() inserted?.forEach { if let entityName = $0.entity.name, let identifier = uniqueIdentifier(for: $0) { insertedIdentifiersAndEntityNames[identifier] = entityName } } let updatedCount = updated?.count ?? 0 let deletedCount = deleted?.count ?? 0 let willHaveChanges = !insertedIdentifiersAndEntityNames.isEmpty || updatedCount > 0 || deletedCount > 0 privateContext.perform { insertedIdentifiersAndEntityNames.forEach({ (identifier, entityName) in let entity = self.syncedEntity(withOriginIdentifier: identifier) if entity == nil { self.createSyncedEntity(identifier: identifier.description, entityName: entityName) } }) debugPrint("QSCloudKitSynchronizer >> Did Save >> Tracking %ld insertions", inserted?.count ?? 0) self.savePrivateContext() if willHaveChanges { self.hasChanges = true DispatchQueue.main.async { NotificationCenter.default.post(name: .ModelAdapterHasChangesNotification, object: self) } } } } } }
mit
7b42c3e4bb331a2fa4c531d8e2e154f8
45.97479
116
0.550089
6.142857
false
false
false
false
studyYF/YueShiJia
YueShiJia/YueShiJia/Classes/Subject/Models/YFSubjectItem.swift
1
1050
// // YFSubjectItem.swift // YueShiJia // // Created by YangFan on 2017/5/17. // Copyright © 2017年 YangFan. All rights reserved. // import UIKit class YFSubjectItem: NSObject { var article_abstract: String? var article_title: String? var article_origin: String? var article_video: String? var article_publish_time: String? var article_id: String? var article_image: String? var top: String? var video_length: String? init(dict: [String : Any]) { super.init() article_abstract = dict["article_abstract"] as? String article_title = dict["article_title"] as? String article_origin = dict["article_origin"] as? String article_video = dict["article_video"] as? String article_publish_time = dict["article_publish_time"] as? String article_id = dict["article_id"] as? String article_image = dict["article_image"] as? String top = dict["top"] as? String video_length = dict["video_length"] as? String } }
apache-2.0
72aa312c14188bb13298fd8e4fcf46ab
22.795455
70
0.627507
3.779783
false
false
false
false
shohei/firefox-ios
Client/Frontend/Browser/TabTrayController.swift
1
27311
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import SnapKit private struct TabTrayControllerUX { static let CornerRadius = CGFloat(4.0) static let BackgroundColor = UIConstants.AppBackgroundColor static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1) static let TextBoxHeight = CGFloat(32.0) static let FaviconSize = CGFloat(18.0) static let Margin = CGFloat(15) static let ToolbarBarTintColor = UIConstants.AppBackgroundColor static let ToolbarButtonOffset = CGFloat(10.0) static let TabTitleTextColor = UIColor.blackColor() static let TabTitleTextFont = UIConstants.DefaultSmallFontBold static let CloseButtonSize = CGFloat(18.0) static let CloseButtonMargin = CGFloat(6.0) static let CloseButtonEdgeInset = CGFloat(10) static let NumberOfColumnsThin = 1 static let NumberOfColumnsWide = 3 static let CompactNumberOfColumnsThin = 2 // Moved from UIConstants temporarily until animation code is merged static var StatusBarHeight: CGFloat { if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact { return 0 } return 20 } } private protocol CustomCellDelegate: class { func customCellDidClose(cell: CustomCell) func cellHeightForCurrentDevice() -> CGFloat } // UIcollectionViewController doesn't let us specify a style for recycling views. We override the default style here. private class CustomCell: UICollectionViewCell { let backgroundHolder: UIView let background: UIImageViewAligned let titleText: UILabel let title: UIVisualEffectView let innerStroke: InnerStrokedView let favicon: UIImageView let closeButton: UIButton var animator: SwipeAnimator! weak var delegate: CustomCellDelegate? // Changes depending on whether we're full-screen or not. var margin = CGFloat(0) override init(frame: CGRect) { self.backgroundHolder = UIView() self.backgroundHolder.backgroundColor = UIColor.whiteColor() self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius self.backgroundHolder.clipsToBounds = true self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor self.background = UIImageViewAligned() self.background.contentMode = UIViewContentMode.ScaleAspectFill self.background.clipsToBounds = true self.background.userInteractionEnabled = false self.background.alignLeft = true self.background.alignTop = true self.favicon = UIImageView() self.favicon.backgroundColor = UIColor.clearColor() self.favicon.layer.cornerRadius = 2.0 self.favicon.layer.masksToBounds = true self.title = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight)) self.title.layer.shadowColor = UIColor.blackColor().CGColor self.title.layer.shadowOpacity = 0.2 self.title.layer.shadowOffset = CGSize(width: 0, height: 0.5) self.title.layer.shadowRadius = 0 self.titleText = UILabel() self.titleText.textColor = TabTrayControllerUX.TabTitleTextColor self.titleText.backgroundColor = UIColor.clearColor() self.titleText.textAlignment = NSTextAlignment.Left self.titleText.userInteractionEnabled = false self.titleText.numberOfLines = 1 self.titleText.font = TabTrayControllerUX.TabTitleTextFont self.closeButton = UIButton() self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal) self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset) self.title.addSubview(self.closeButton) self.title.addSubview(self.titleText) self.title.addSubview(self.favicon) self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame) self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor super.init(frame: frame) self.opaque = true self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self) self.closeButton.addTarget(self.animator, action: "SELcloseWithoutGesture", forControlEvents: UIControlEvents.TouchUpInside) contentView.addSubview(backgroundHolder) backgroundHolder.addSubview(self.background) backgroundHolder.addSubview(innerStroke) backgroundHolder.addSubview(self.title) self.accessibilityCustomActions = [ UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture") ] } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private override func layoutSubviews() { super.layoutSubviews() let w = frame.width let h = frame.height backgroundHolder.frame = CGRect(x: margin, y: margin, width: w, height: h) background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size) title.frame = CGRect(x: 0, y: 0, width: backgroundHolder.frame.width, height: TabTrayControllerUX.TextBoxHeight) favicon.frame = CGRect(x: 6, y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2, width: TabTrayControllerUX.FaviconSize, height: TabTrayControllerUX.FaviconSize) let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6 titleText.frame = CGRect(x: titleTextLeft, y: 0, width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2, height: title.frame.height) innerStroke.frame = background.frame closeButton.snp_makeConstraints { make in make.size.equalTo(title.snp_height) make.trailing.centerY.equalTo(title) } var top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0 titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top)) } private override func prepareForReuse() { // Reset any close animations. backgroundHolder.transform = CGAffineTransformIdentity backgroundHolder.alpha = 1 } func showFullscreen(container: UIView, table: UICollectionView, shouldOffset: Bool) { var offset: CGFloat = shouldOffset ? 2 : 1 frame = CGRect(x: 0, y: container.frame.origin.y + UIConstants.ToolbarHeight + TabTrayControllerUX.StatusBarHeight, width: container.frame.width, height: container.frame.height - (UIConstants.ToolbarHeight * offset + TabTrayControllerUX.StatusBarHeight)) container.insertSubview(self, atIndex: container.subviews.count) } func showAt(index: Int, container: UIView, table: UICollectionView) { let scrollOffset = table.contentOffset.y + table.contentInset.top if table.numberOfItemsInSection(0) > 0 { if let attr = table.collectionViewLayout.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) { frame = CGRectOffset(attr.frame, -container.frame.origin.x, -container.frame.origin.y + UIConstants.ToolbarHeight + TabTrayControllerUX.StatusBarHeight - scrollOffset) } } else { // TODO: fix this so the frame is where the first item *would* be frame = CGRect(x: 0, y: TabTrayControllerUX.Margin + UIConstants.ToolbarHeight + TabTrayControllerUX.StatusBarHeight, width: container.frame.width, height: self.delegate!.cellHeightForCurrentDevice()) } container.insertSubview(self, atIndex: container.subviews.count) } var tab: Browser? { didSet { titleText.text = tab?.title if let favIcon = tab?.displayFavicon { favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!) } } } } class TabTrayController: UIViewController, UITabBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var tabManager: TabManager! private let CellIdentifier = "CellIdentifier" var collectionView: UICollectionView! var profile: Profile! var numberOfColumns: Int { let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true // iPhone 4-6+ portrait if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular { return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin } else { return TabTrayControllerUX.NumberOfColumnsWide } } var navBar: UIView! var addTabButton: UIButton! var settingsButton: UIButton! var statusBarFrame: CGRect { return UIApplication.sharedApplication().statusBarFrame } var collectionViewTransitionSnapshot: UIView? func SELstatusBarFrameDidChange(notification: NSNotification) { self.view.setNeedsUpdateConstraints() } override func viewDidLoad() { super.viewDidLoad() view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.") tabManager.addDelegate(self) navBar = UIView() navBar.backgroundColor = TabTrayControllerUX.BackgroundColor let signInButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton signInButton.addTarget(self, action: "SELdidClickDone", forControlEvents: UIControlEvents.TouchUpInside) signInButton.setTitle(NSLocalizedString("Sign in", comment: "Button that leads to Sign in section of the Settings sheet."), forState: UIControlState.Normal) signInButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) // workaround for VoiceOver bug - if we create the button with UIButton.buttonWithType, // it gets initial frame with height 0 and accessibility somehow does not update the height // later and thus the button becomes completely unavailable to VoiceOver unless we // explicitly set the height to some (reasonable) non-zero value. // Also note that setting accessibilityFrame instead of frame has no effect. signInButton.frame.size.height = signInButton.intrinsicContentSize().height let navItem = UINavigationItem() navItem.titleView = signInButton signInButton.hidden = true //hiding sign in button until we decide on UX addTabButton = UIButton() addTabButton.setImage(UIImage(named: "add"), forState: .Normal) addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside) addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.") settingsButton = UIButton() settingsButton.setImage(UIImage(named: "settings"), forState: .Normal) settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside) settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.") let flowLayout = UICollectionViewFlowLayout() collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout) collectionView.dataSource = self collectionView.delegate = self collectionView.registerClass(CustomCell.self, forCellWithReuseIdentifier: CellIdentifier) collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor view.addSubview(collectionView) view.addSubview(navBar) view.addSubview(addTabButton) view.addSubview(settingsButton) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "SELstatusBarFrameDidChange:", name: UIApplicationDidChangeStatusBarFrameNotification, object: nil) collectionView.reloadData() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(true) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidChangeStatusBarFrameNotification, object: nil) } override func updateViewConstraints() { super.updateViewConstraints() navBar.snp_remakeConstraints { make in let topLayoutGuide = self.topLayoutGuide as! UIView make.top.equalTo(topLayoutGuide.snp_bottom) make.height.equalTo(UIConstants.ToolbarHeight) make.left.right.equalTo(self.view) } addTabButton.snp_remakeConstraints { make in make.trailing.bottom.equalTo(self.navBar) make.size.equalTo(UIConstants.ToolbarHeight) } settingsButton.snp_remakeConstraints { make in make.leading.bottom.equalTo(self.navBar) make.size.equalTo(UIConstants.ToolbarHeight) } collectionView.snp_remakeConstraints { make in make.top.equalTo(navBar.snp_bottom) make.left.right.bottom.equalTo(self.view) } } func cellHeightForCurrentDevice() -> CGFloat { let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5) if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact { return shortHeight } else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact { return shortHeight } else { return TabTrayControllerUX.TextBoxHeight * 8 } } func SELdidClickDone() { presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } func SELdidClickSettingsItem() { let controller = SettingsNavigationController() controller.profile = profile controller.tabManager = tabManager controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet presentViewController(controller, animated: true, completion: nil) } func SELdidClickAddTab() { // We're only doing one update here, but using a batch update lets us delay selecting the tab // until after its insert animation finishes. self.collectionView.performBatchUpdates({ _ in let tab = self.tabManager.addTab() self.tabManager.selectTab(tab) }, completion: { finished in if finished { self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } }) } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let tab = tabManager[indexPath.item] tabManager.selectTab(tab) dispatch_async(dispatch_get_main_queue()) { _ in self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! CustomCell cell.animator.delegate = self cell.delegate = self if let tab = tabManager[indexPath.item] { cell.titleText.text = tab.displayTitle if !tab.displayTitle.isEmpty { cell.accessibilityLabel = tab.displayTitle } else { cell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url) } cell.isAccessibilityElement = true if let favIcon = tab.displayFavicon { cell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!) } else { cell.favicon.image = UIImage(named: "defaultFavicon") } cell.background.image = tab.screenshot } return cell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return tabManager.count } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return TabTrayControllerUX.Margin } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let cellWidth = (collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns) return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice()) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return TabTrayControllerUX.Margin } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) collectionView.collectionViewLayout.invalidateLayout() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } } extension TabTrayController: Transitionable { private func getTransitionCell(options: TransitionOptions, browser: Browser?) -> CustomCell { var transitionCell: CustomCell if let cell = options.moving as? CustomCell { transitionCell = cell } else { transitionCell = CustomCell(frame: options.container!.frame) options.moving = transitionCell } transitionCell.background.image = browser?.screenshot transitionCell.titleText.text = browser?.displayTitle if let favIcon = browser?.displayFavicon { transitionCell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!) } return transitionCell } func transitionablePreShow(transitionable: Transitionable, options: TransitionOptions) { self.view.layoutSubviews() self.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: tabManager.selectedIndex, inSection: 0), atScrollPosition: .CenteredVertically, animated: false) if let container = options.container { let cell = getTransitionCell(options, browser: tabManager.selectedTab) cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius cell.innerStroke.hidden = true } navBar.hidden = true collectionView.backgroundColor = UIColor.clearColor() view.layoutIfNeeded() collectionViewTransitionSnapshot = snapshotTransitionView(collectionView) self.view.addSubview(collectionViewTransitionSnapshot!) collectionViewTransitionSnapshot?.transform = CGAffineTransformMakeScale(0.9, 0.9) collectionViewTransitionSnapshot?.alpha = 0 } func transitionablePreHide(transitionable: Transitionable, options: TransitionOptions) { self.collectionView.layoutSubviews() if let container = options.container { let cell = getTransitionCell(options, browser: tabManager.selectedTab) cell.backgroundHolder.layer.cornerRadius = 0 cell.innerStroke.hidden = true } navBar.hidden = true collectionView.backgroundColor = UIColor.clearColor() collectionViewTransitionSnapshot = snapshotTransitionView(collectionView) self.view.addSubview(collectionViewTransitionSnapshot!) } func transitionableWillHide(transitionable: Transitionable, options: TransitionOptions) { // Create a fake cell that is shown fullscreen if let container = options.container { let cell = getTransitionCell(options, browser: tabManager.selectedTab) var hasToolbar = false if let fromView = options.fromView as? BrowserViewController { hasToolbar = fromView.shouldShowToolbarForTraitCollection(self.traitCollection) } else if let toView = options.toView as? BrowserViewController { hasToolbar = toView.shouldShowToolbarForTraitCollection(self.traitCollection) } cell.showFullscreen(container, table: collectionView, shouldOffset: hasToolbar) cell.layoutIfNeeded() options.cellFrame = cell.frame cell.title.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, 0, -cell.title.frame.height) } collectionViewTransitionSnapshot?.transform = CGAffineTransformMakeScale(0.9, 0.9) collectionViewTransitionSnapshot?.alpha = 0 let buttonOffset = addTabButton.frame.width + TabTrayControllerUX.ToolbarButtonOffset addTabButton.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, buttonOffset , 0) settingsButton.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, -buttonOffset , 0) } func transitionableWillShow(transitionable: Transitionable, options: TransitionOptions) { if let container = options.container { // Create a fake cell that is at the selected index let cell = getTransitionCell(options, browser: tabManager.selectedTab) cell.showAt(tabManager.selectedIndex, container: container, table: collectionView) cell.layoutIfNeeded() options.cellFrame = cell.frame } collectionViewTransitionSnapshot?.transform = CGAffineTransformIdentity collectionViewTransitionSnapshot?.alpha = 1 addTabButton.transform = CGAffineTransformIdentity settingsButton.transform = CGAffineTransformIdentity navBar.alpha = 1 } func transitionableWillComplete(transitionable: Transitionable, options: TransitionOptions) { if let cell = options.moving as? CustomCell { cell.removeFromSuperview() cell.innerStroke.alpha = 0 cell.innerStroke.hidden = false collectionViewTransitionSnapshot?.removeFromSuperview() collectionView.hidden = false navBar.hidden = false collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor if let tab = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: tabManager.selectedIndex, inSection: 0)) as? CustomCell { UIView.animateWithDuration(0.55, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { _ in cell.innerStroke.alpha = 1 }, completion: { _ in return }) } } } private func snapshotTransitionView(view: UIView) -> UIView { let snapshot = view.snapshotViewAfterScreenUpdates(true) snapshot.frame = view.frame view.hidden = true return snapshot } } extension TabTrayController: SwipeAnimatorDelegate { func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) { let tabCell = animator.container as! CustomCell if let indexPath = self.collectionView.indexPathForCell(tabCell) { if let tab = tabManager[indexPath.item] { tabManager.removeTab(tab) } } } } extension TabTrayController: TabManagerDelegate { func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) { // Our UI doesn't care about what's selected } func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) { } func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex index: Int, restoring: Bool) { self.collectionView.performBatchUpdates({ _ in self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)]) }, completion: { finished in if finished { tabManager.selectTab(tabManager[index]) self.presentingViewController!.dismissViewControllerAnimated(true, completion: nil) } }) } func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex index: Int) { var newTab: Browser? = nil self.collectionView.performBatchUpdates({ _ in self.collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)]) }, completion: { finished in if tabManager.count == 0 { newTab = tabManager.addTab() } }) } func tabManagerDidRestoreTabs(tabManager: TabManager) { } } extension TabTrayController: CustomCellDelegate { private func customCellDidClose(cell: CustomCell) { let indexPath = collectionView.indexPathForCell(cell)! if let tab = tabManager[indexPath.item] { tabManager.removeTab(tab) } } } // A transparent view with a rectangular border with rounded corners, stroked // with a semi-transparent white border. private class InnerStrokedView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let strokeWidth = 1.0 as CGFloat let halfWidth = strokeWidth/2 as CGFloat let path = UIBezierPath(roundedRect: CGRect(x: halfWidth, y: halfWidth, width: rect.width - strokeWidth, height: rect.height - strokeWidth), cornerRadius: TabTrayControllerUX.CornerRadius) path.lineWidth = strokeWidth UIColor.whiteColor().colorWithAlphaComponent(0.2).setStroke() path.stroke() } }
mpl-2.0
09ca52ba3ec5685e97ef7e4d412f0911
41.673438
227
0.696679
5.749684
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/Pods/Swiftilities/Pod/Classes/ImageHelpers/UIImage+Tinting.swift
1
2530
// // UIImage+Tinting.swift // Swiftilities // // Created by Nick Bonatsakis on 5/1/17. // Copyright © 2017 Raizlabs. All rights reserved. // import Foundation import UIKit // Originally sourced from BonMot: https://github.com/Raizlabs/BonMot/blob/master/Sources/Image%2BTinting.swift // Please apply any improvments made here to source. public extension UIImage { /// Returns a copy of the receiver where the alpha channel is maintained, /// but every pixel's color is replaced with `color`. /// /// - note: The returned image does _not_ have the template flag set, /// preventing further tinting. /// /// - Parameter theColor: The color to use to tint the receiver. /// - Returns: A tinted copy of the image. func rz_tintedImage(color theColor: UIColor) -> UIImage { let imageRect = CGRect(origin: .zero, size: size) // Save original properties let originalCapInsets = capInsets let originalResizingMode = resizingMode let originalAlignmentRectInsets = alignmentRectInsets UIGraphicsBeginImageContextWithOptions(size, false, scale) guard let context = UIGraphicsGetCurrentContext() else { return self } // Flip the context vertically context.translateBy(x: 0.0, y: size.height) context.scaleBy(x: 1.0, y: -1.0) // Image tinting mostly inspired by http://stackoverflow.com/a/22528426/255489 context.setBlendMode(.normal) context.draw(cgImage!, in: imageRect) // .sourceIn: resulting color = source color * destination alpha context.setBlendMode(.sourceIn) context.setFillColor(theColor.cgColor) context.fill(imageRect) // Get new image guard var image = UIGraphicsGetImageFromCurrentImageContext() else { return self } UIGraphicsEndImageContext() // Prevent further tinting image = image.withRenderingMode(.alwaysOriginal) // Restore original properties image = image.withAlignmentRectInsets(originalAlignmentRectInsets) if originalCapInsets != image.capInsets || originalResizingMode != image.resizingMode { image = image.resizableImage(withCapInsets: originalCapInsets, resizingMode: originalResizingMode) } // Transfer accessibility label (watchOS not included; does not have accessibilityLabel on UIImage). image.accessibilityLabel = self.accessibilityLabel return image } }
mit
8835785dfc3da986b6012d2b705c441d
35.128571
111
0.677343
5.078313
false
false
false
false
hstdt/GodEye
Carthage/Checkouts/AppBaseKit/AppBaseKit/Classes/Extension/UIKit/UIColor+AppBaseKit.swift
1
3304
// // UIColor+AppBaseKit.swift // Pods // // Created by zixun on 16/9/25. // // import Foundation import UIKit extension UIColor { public class func niceBlack() -> UIColor { return UIColor(red: 30.0/255.0, green: 32.0/255.0, blue: 40.0/255.0, alpha: 1) } public class func niceDuckBlack() -> UIColor { return UIColor(red: 20.0/255.0, green: 21.0/255.0, blue: 27.0/255.0, alpha: 1) } public class func niceRed() -> UIColor { return UIColor(red: 237.0/255.0, green: 66.0/255.0, blue: 82.0/255.0, alpha: 1) } public class func niceJHSRed() -> UIColor { return UIColor(red: 235.0/255.0, green: 0.0/255.0, blue: 18.0/255.0, alpha: 1) } } // MARK: - RGB extension UIColor { public convenience init(hex:Int, alpha:CGFloat = 1.0) { let red: CGFloat = CGFloat((hex & 0xFF0000) >> 16) / 255.0 let green: CGFloat = CGFloat((hex & 0x00FF00) >> 8) / 255.0 let blue: CGFloat = CGFloat((hex & 0x0000FF)) / 255.0 self.init(red: red, green: green, blue: blue, alpha: alpha) } public convenience init?(hexString:String,alpha:CGFloat = 1.0) { let formatted = hexString.replacingOccurrences(of: "0x", with: "") .replacingOccurrences(of:"#", with: "") if let hex = Int(formatted, radix: 16) { self.init(hex: hex, alpha: alpha) } return nil } public func hexString(prefix:String = "") -> String { let rgbFloat = self.rgba() let result = self.string(of: rgbFloat.r) + self.string(of: rgbFloat.g) + self.string(of: rgbFloat.b) return prefix + result.uppercased() } private func string(of component:Int) -> String { var result = String(format: "%x", component) let count = result.characters.count if count == 0 { return "00" }else if count == 1 { return "0" + result }else { return result } } public func hex() -> Int? { return Int(self.hexString(), radix: 16) } public func rgba() -> (r:Int,g:Int,b:Int,a:CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) r = r * 255 g = g * 255 b = b * 255 return (Int(r),Int(g),Int(b),a) } } // MARK: - Gradient extension UIColor { public class func gradient(startColor:UIColor,endColor:UIColor,fraction:CGFloat) -> UIColor { var startR: CGFloat = 0, startG: CGFloat = 0, startB: CGFloat = 0, startA: CGFloat = 0 startColor.getRed(&startR, green: &startG, blue: &startB, alpha: &startA) var endR: CGFloat = 0, endG: CGFloat = 0, endB: CGFloat = 0, endA: CGFloat = 0 endColor.getRed(&endR, green: &endG, blue: &endB, alpha: &endA) let resultA = startA + (endA - startA) * fraction let resultR = startR + (endR - startR) * fraction let resultG = startG + (endG - startG) * fraction let resultB = startB + (endB - startB) * fraction return UIColor(red: resultR, green: resultG, blue: resultB, alpha: resultA) } }
mit
a6a7d4ceeea843f866241615486fcd07
30.466667
108
0.555085
3.470588
false
false
false
false
WeirdMath/SwiftyHaru
Sources/SwiftyHaru/Graphics/Color.swift
1
14740
// // Color.swift // SwiftyHaru // // Created by Sergej Jaskiewicz on 03.10.16. // // #if SWIFT_PACKAGE import CLibHaru #endif /// This structure represents a color. Property values must be between 0 and 1. /// /// Supported color spaces: /// * `PDFColorSpace.deviceRGB` /// * `PDFColorSpace.deviceCMYK` /// * `PDFColorSpace.deviceGray` public struct Color: Hashable { /// Returns the red color in `PDFColorSpace.deviceRGB` space public static let red = Color(red: 1, green: 0, blue: 0)! /// Returns the green color in `PDFColorSpace.deviceRGB` space public static let green = Color(red: 0, green: 1, blue: 0)! /// Returns the blue color in `PDFColorSpace.deviceRGB` space public static let blue = Color(red: 0, green: 0, blue: 1)! /// Returns the black color in `PDFColorSpace.deviceGray` space public static let black = Color(gray: 0)! /// Returns the white color in `PDFColorSpace.deviceGray` space public static let white = Color(gray: 1)! /// Returns the transparent white color in `PDFColorSpace.deviceGray` space public static let clear = Color(gray: 1, alpha: 0)! internal enum _ColorSpaceWrapper: Hashable { case rgb(red: Float, green: Float, blue: Float) case cmyk(cyan: Float, magenta: Float, yellow: Float, black: Float) case gray(Float) } internal var _wrapped: _ColorSpaceWrapper /// The color space associated with the color. public var colorSpace: PDFColorSpace { switch _wrapped { case .rgb: return .deviceRGB case .cmyk: return .deviceCMYK case .gray: return .deviceGray } } /// The value of the alpha component associated with the color. public var alpha: Float = 1 /// The direct value of the red component associated with the color if the `colorSpace` is `.deviceRGB`, or /// the computed value otherwise. public var red: Float { get { switch _wrapped { case .rgb(let color): return color.red case .cmyk(let color): return (1 - color.cyan) * (1 - color.black) case .gray(let color): return color } } set { switch _wrapped { case .rgb(let color): _wrapped = .rgb(red: newValue, green: color.green, blue: color.blue) case .cmyk: let newBlack = 1 - max(newValue, green, blue) _wrapped = .cmyk(cyan: newBlack < 1 ? (1 - newValue - newBlack) / (1 - newBlack) : 0, magenta: newBlack < 1 ? (1 - green - newBlack) / (1 - newBlack) : 0, yellow: newBlack < 1 ? (1 - blue - newBlack) / (1 - newBlack) : 0, black: newBlack) case .gray: _wrapped = .gray(newValue) } } } /// The direct value of the green component associated with the color if the `colorSpace` is `.deviceRGB`, or /// the computed value otherwise. public var green: Float { get { switch _wrapped { case .rgb(let color): return color.green case .cmyk(let color): return (1 - color.magenta) * (1 - color.black) case .gray(let color): return color } } set { switch _wrapped { case .rgb(let color): _wrapped = .rgb(red: color.red, green: newValue, blue: color.blue) case .cmyk: let newBlack = 1 - max(red, newValue, blue) _wrapped = .cmyk(cyan: newBlack < 1 ? (1 - red - newBlack) / (1 - newBlack) : 0, magenta: newBlack < 1 ? (1 - newValue - newBlack) / (1 - newBlack) : 0, yellow: newBlack < 1 ? (1 - blue - newBlack) / (1 - newBlack) : 0, black: newBlack) case .gray: _wrapped = .gray(newValue) } } } /// The direct value of the blue component associated with the color if the `colorSpace` is `.deviceRGB`, or /// the computed value otherwise. public var blue: Float { get { switch _wrapped { case .rgb(let color): return color.blue case .cmyk(let color): return (1 - color.yellow) * (1 - color.black) case .gray(let color): return color } } set { switch _wrapped { case .rgb(let color): _wrapped = .rgb(red: color.red, green: color.green, blue: newValue) case .cmyk: let newBlack = 1 - max(red, green, newValue) _wrapped = .cmyk(cyan: newBlack < 1 ? (1 - red - newBlack) / (1 - newBlack) : 0, magenta: newBlack < 1 ? (1 - green - newBlack) / (1 - newBlack) : 0, yellow: newBlack < 1 ? (1 - newValue - newBlack) / (1 - newBlack) : 0, black: newBlack) case .gray: _wrapped = .gray(newValue) } } } /// The direct value of the cyan component associated with the color if the `colorSpace` is `.deviceCMYK`, or /// the computed value otherwise. public var cyan: Float { get { switch _wrapped { case .cmyk(let color): return color.cyan case .rgb(let color): return black < 1 ? (1 - color.red - black) / (1 - black) : 0 case .gray: return 0 } } set { switch _wrapped { case .cmyk(let color): _wrapped = .cmyk(cyan: newValue, magenta: color.magenta, yellow: color.yellow, black: color.black) case .rgb: _wrapped = .rgb(red: (1 - newValue) * (1 - black), green: (1 - magenta) * (1 - black), blue: (1 - yellow) * (1 - black)) case .gray: return } } } /// The direct value of the magenta component associated with the color if the `colorSpace` is `.deviceCMYK`, /// or the computed value otherwise. public var magenta: Float { get { switch _wrapped { case .cmyk(let color): return color.magenta case .rgb(let color): return black < 1 ? (1 - color.green - black) / (1 - black) : 0 default: return 0 } } set { switch _wrapped { case .cmyk(let color): _wrapped = .cmyk(cyan: color.cyan, magenta: newValue, yellow: color.yellow, black: color.black) case .rgb: _wrapped = .rgb(red: (1 - cyan) * (1 - black), green: (1 - newValue) * (1 - black), blue: (1 - yellow) * (1 - black)) case .gray: return } } } /// The direct value of the yellow component associated with the color if the `colorSpace` is `.deviceCMYK`, or /// the computed value otherwise. public var yellow: Float { get { switch _wrapped { case .cmyk(let color): return color.yellow case .rgb(let color): return black < 1 ? (1 - color.blue - black) / (1 - black) : 0 default: return 0 } } set { switch _wrapped { case .cmyk(let color): _wrapped = .cmyk(cyan: color.cyan, magenta: color.magenta, yellow: newValue, black: color.black) case .rgb: _wrapped = .rgb(red: (1 - cyan) * (1 - black), green: (1 - magenta) * (1 - black), blue: (1 - newValue) * (1 - black)) case .gray: return } } } /// The direct value of the black component associated with the color if the `colorSpace` is `.deviceCMYK` /// or `.deviceGray`, or the computed value otherwise. public var black: Float { get { switch _wrapped { case .cmyk(let color): return color.black case .rgb(let color): return 1 - max(color.red, color.green, color.blue) case .gray(let color): return color } } set { switch _wrapped { case .cmyk(let color): _wrapped = .cmyk(cyan: color.cyan, magenta: color.magenta, yellow: color.yellow, black: newValue) case .rgb: _wrapped = .rgb(red: (1 - cyan) * (1 - newValue), green: (1 - magenta) * (1 - newValue), blue: (1 - yellow) * (1 - newValue)) case .gray: _wrapped = .gray(newValue) } } } /// Creates a color with the RGB color model. /// /// For each parameter valid values are between 0 and 1. /// /// - Parameters: /// - red: The red component of the color. /// - green: The green component of the color. /// - blue: The blue component of the color. /// - alpha: The alpha component of the color. Default value is 1. /// /// - Returns: The color with the specified components, or `nil` if the values specified were invalid. public init?(red: Float, green: Float, blue: Float, alpha: Float = 1) { guard (red >= 0 && red <= 1) && (green >= 0 && green <= 1) && (blue >= 0 && blue <= 1) && (alpha >= 0 && alpha <= 1) else { return nil } _wrapped = .rgb(red: red, green: green, blue: blue) self.alpha = alpha } /// Creates a color with the CMYK color model. /// /// For each parameter valid values are between 0 and 1. /// /// - Parameters: /// - cyan: The cyan component of the color. /// - magenta: The magenta component of the color. /// - yellow: The yellow component of the color. /// - black: The black component of the color. /// - alpha: The alpha component of the color. Default value is 1. /// /// - Returns: The color with the specified components, or `nil` if the values specified were invalid. public init?(cyan: Float, magenta: Float, yellow: Float, black: Float, alpha: Float = 1) { guard (cyan >= 0 && cyan <= 1) && (magenta >= 0 && magenta <= 1) && (yellow >= 0 && yellow <= 1) && (black >= 0 && black <= 1) && (alpha >= 0 && alpha <= 1) else { return nil } _wrapped = .cmyk(cyan: cyan, magenta: magenta, yellow: yellow, black: black) self.alpha = alpha } /// Creates a color with the gray shades color model. /// /// For each parameter valid values are between 0 and 1. /// /// - Parameters: /// - gray: The gray component of the color. /// - alpha: The alpha component of the color. Default value is 1. /// /// - Returns: The color with the specified components, or `nil` if the values specified were invalid. public init?(gray: Float, alpha: Float = 1) { guard gray >= 0 && gray <= 1 else { return nil } _wrapped = .gray(gray) self.alpha = alpha } /// Converts the color to the specified color space. /// /// Supported color spaces: /// * `PDFColorSpace.deviceRGB` /// * `PDFColorSpace.deviceCMYK` /// * `PDFColorSpace.deviceGray` /// /// - Parameter colorSpace: The color space to convert the color to. public mutating func convert(to colorSpace: PDFColorSpace) { switch colorSpace { case .deviceRGB: _wrapped = .rgb(red: red, green: green, blue: blue) case .deviceCMYK: _wrapped = .cmyk(cyan: cyan, magenta: magenta, yellow: yellow, black: black) case .deviceGray: _wrapped = .gray(black) default: assertionFailure("The color space \(colorSpace) is not supported yet") } } /// Creates a new color by converting the current color to the specified color space. /// /// Supported color spaces: /// * `PDFColorSpace.deviceRGB` /// * `PDFColorSpace.deviceCMYK` /// * `PDFColorSpace.deviceGray` /// /// - Parameter colorSpace: The color space of the new color. /// - Returns: The new color with the specified color space. @inlinable public func converting(to colorSpace: PDFColorSpace) -> Color { var newColor = self newColor.convert(to: colorSpace) return newColor } } extension Color: CustomDebugStringConvertible { public var debugDescription: String { var result = "\(String(describing: Color.self))(" switch _wrapped { case let .rgb(red, green, blue): result += "red: \(red), green: \(green), blue: \(blue)" case let .cmyk(cyan, magenta, yellow, black): result += "cyan: \(cyan), magenta: \(magenta), yellow: \(yellow), black: \(black)" case let .gray(gray): result += "gray: \(gray)" } result += ")" return result } } extension Color: _ExpressibleByColorLiteral { public init(_colorLiteralRed red: Float, green: Float, blue: Float, alpha: Float) { self.init(red: red, green: green, blue: blue, alpha: alpha)! } } extension Color { internal init(_ haruRGBColor: HPDF_RGBColor) { self.init(red: haruRGBColor.r, green: haruRGBColor.g, blue: haruRGBColor.b)! } internal init(_ haruCMYKColor: HPDF_CMYKColor) { self.init(cyan: haruCMYKColor.c, magenta: haruCMYKColor.m, yellow: haruCMYKColor.y, black: haruCMYKColor.k)! } }
mit
960308236cf6c8167288dca09011e239
35.305419
115
0.498575
4.566295
false
false
false
false
SpriteKitAlliance/SKAControlSprite
Example/SKAControlExample/SKAControlExample/Sprites/TwoPaneButton.swift
1
3643
// // TwoPaneButton.swift // SKASimpleButtonExample // // Created by Marc Vandehey on 4/18/17. // Copyright © 2017 SpriteKit Alliance. All rights reserved. // import SpriteKit /** Example usage: let controlTestButton = TwoPaneButton(size: CGSize(width: frame.size.width * 0.75, height: 50)) controlTestButton.setup(text: "Control Test!", fontSize: 30, autoResize: false) controlTestButton.addTarget(self, selector: #selector(navigateToControlTest(_:)), forControlEvents: .TouchUpInside) addChild(controlTestButton) . . . func navigateToSliderFun(_ button : TwoPaneButton) { //Button clicked } */ class TwoPaneButton : SKAControlSprite { private var foregroundPane : SKSpriteNode! private var backgroundPane : SKSpriteNode! private var label : SKLabelNode! private var zeroPosition = CGPoint.zero var fontName = "Avenir-Black" init(size : CGSize) { super.init(texture: nil, color: .clear, size: size) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override var zPosition: CGFloat { didSet { foregroundPane.zPosition = zPosition + 1 label.zPosition = zPosition + 2 } } override var size: CGSize { didSet { updateLayout() } } var elevation : CGFloat = 10 { didSet { updateLayout() } } var foregroundColor : SKColor { get { return foregroundPane.color } set { foregroundPane.color = newValue } } var fontColor : SKColor { get { return label.fontColor! } set { label.fontColor = newValue } } var backgroundColor : SKColor { get { return backgroundPane.color } set { backgroundPane.color = newValue } } func setup() { self.color = .clear backgroundPane = SKSpriteNode(color: SKColor(red:0.79, green:0.76, blue:0.37, alpha:1.0), size: size) backgroundPane.position = zeroPosition foregroundPane = SKSpriteNode(color: SKColor(red:0.99, green:0.92, blue:0.55, alpha:1.0), size: size) foregroundPane.anchorPoint = anchorPoint backgroundPane.anchorPoint = anchorPoint label = SKLabelNode(fontNamed: fontName) label.fontColor = SKColor(red:0.29, green:0.29, blue:0.29, alpha:1.0) label.horizontalAlignmentMode = .center label.verticalAlignmentMode = .center addChild(backgroundPane) addChild(foregroundPane) foregroundPane.addChild(label) zPosition = 0 } func setup(text: String, fontSize: CGFloat, autoResize: Bool) { label.text = text label.fontSize = fontSize if autoResize { let newSize = CGSize(width: label.frame.width + label.frame.width * 0.4, height: label.frame.height * 2) size.width = max(size.width, newSize.width) size.height = max(size.height, newSize.width) } updateLayout() } private func updateLayout() { if backgroundPane == nil { return } zeroPosition = CGPoint(x: -elevation, y: -elevation) backgroundPane.position = zeroPosition var buttonSize = size buttonSize.height -= elevation buttonSize.width -= elevation backgroundPane.size = buttonSize foregroundPane.size = buttonSize if anchorPoint == CGPoint(x: 0, y: 1) { label.position = CGPoint(x: buttonSize.width / 2, y: -buttonSize.height / 2) } } override func updateControl() { if controlState.contains(.Highlighted) { foregroundPane.run(SKAction.move(to: zeroPosition, duration: 0.05)) } else if controlState.contains(.Normal) { foregroundPane.run(SKAction.move(to: CGPoint.zero, duration: 0.05)) } } }
mit
12354ef2d060f3fa6fc06713daaab9a0
21.7625
116
0.66749
4.087542
false
false
false
false
TabletopAssistant/DiceKit
DiceKit/Die.Roll.swift
1
1206
// // Die.Roll.swift // DiceKit // // Created by Brentley Jones on 7/18/15. // Copyright © 2015 Brentley Jones. All rights reserved. // import Foundation extension Die { /// The result of rolling a `Die`. public struct Roll: Equatable { public let die: Die public let value: Int public init(die: Die, value: Int) { self.die = die self.value = value } } } // MARK: - ExpressionResultType extension Die.Roll: ExpressionResultType { public var resultValue: ExpressionResultValue { return ExpressionResultValue(integerLiteral: value) } } // MARK: - CustomStringConvertible extension Die.Roll: CustomStringConvertible { public var description: String { get { return "\(value)|\(die.sides)" } } } // MARK: - CustomDebugStringConvertible extension Die.Roll: CustomDebugStringConvertible { public var debugDescription: String { return "\(String(reflecting: die)).Roll(\(value))" } } // MARK: - Equatable public func == (lhs: Die.Roll, rhs: Die.Roll) -> Bool { return lhs.die == rhs.die && lhs.value == rhs.value }
apache-2.0
93f115e51eafcb085291015f5d56acba
18.435484
59
0.604979
4.213287
false
false
false
false
fuzongjian/SwiftStudy
SwiftStudy/Basis/BasisController.swift
1
2266
// // BasisController.swift // SwiftStudy // // Created by 付宗建 on 16/8/15. // Copyright © 2016年 youran. All rights reserved. // import UIKit class BasisController: SuperViewController,UITableViewDelegate,UITableViewDataSource{ let cellID = "cell" var tableView : UITableView? var items : NSArray? var controllers : NSArray? override func viewDidLoad() { super.viewDidLoad() configBasisControllerUI() } func configBasisControllerUI() { items = ["基础部分(Foundation)","字符串和字符(StringCharacters)","集合类型(CollectionTypes)","控制流(ControlFlow)","函数(Function)","闭包(Closures)","字符串的截取(Range)"] controllers = ["FoundationViewController","StringCharactersController","CollectionTypesController","ControlFlowController","ClosuresController","FunctionController","RangeViewController"] tableView = UITableView.init(frame: self.view.bounds, style: .Plain) tableView?.delegate = self tableView?.dataSource = self self.view.addSubview(tableView!) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(cellID) if cell == nil { cell = UITableViewCell.init(style: .Default, reuseIdentifier: cellID) } cell?.textLabel?.text = items?.objectAtIndex(indexPath.row) as? String cell?.textLabel?.textAlignment = .Center return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let controllerStr = controllers?.objectAtIndex(indexPath.row) as? String let ControllerName = NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String + "." + controllerStr! let aClass = NSClassFromString(ControllerName) as! UIViewController.Type let nextController = aClass.init() nextController.title = items?.objectAtIndex(indexPath.row) as? String self.navigationController?.pushViewController(nextController, animated: true) } }
apache-2.0
04d5ee69c7149297a2160f7fb2ec7259
43.959184
195
0.703132
5.064368
false
false
false
false
hughbe/swift
test/SILGen/closures.swift
3
39557
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s import Swift var zero = 0 // <rdar://problem/15921334> // CHECK-LABEL: sil hidden @_T08closures46return_local_generic_function_without_captures{{[_0-9a-zA-Z]*}}F : $@convention(thin) <A, R> () -> @owned @callee_owned (@in A) -> @out R { func return_local_generic_function_without_captures<A, R>() -> (A) -> R { func f(_: A) -> R { Builtin.int_trap() } // CHECK: [[FN:%.*]] = function_ref @_T08closures46return_local_generic_function_without_captures{{[_0-9a-zA-Z]*}} : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1 // CHECK: [[FN_WITH_GENERIC_PARAMS:%.*]] = partial_apply [[FN]]<A, R>() : $@convention(thin) <τ_0_0, τ_0_1> (@in τ_0_0) -> @out τ_0_1 // CHECK: return [[FN_WITH_GENERIC_PARAMS]] : $@callee_owned (@in A) -> @out R return f } func return_local_generic_function_with_captures<A, R>(_ a: A) -> (A) -> R { func f(_: A) -> R { _ = a } return f } // CHECK-LABEL: sil hidden @_T08closures17read_only_captureS2iF : $@convention(thin) (Int) -> Int { func read_only_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // SEMANTIC ARC TODO: This is incorrect. We need to do the project_box on the copy. // CHECK: [[PROJECT:%.*]] = project_box [[XBOX]] // CHECK: store [[X]] to [trivial] [[PROJECT]] func cap() -> Int { return x } return cap() // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // SEMANTIC ARC TODO: See above. This needs to happen on the copy_valued box. // CHECK: mark_function_escape [[PROJECT]] // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_T08closures17read_only_capture.*]] : $@convention(thin) (@owned { var Int }) -> Int // CHECK: [[RET:%[0-9]+]] = apply [[CAP]]([[XBOX_COPY]]) // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: } // end sil function '_T08closures17read_only_captureS2iF' // CHECK: sil private @[[CAP_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : ${ var Int }): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int // CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]] // CHECK: destroy_value [[XBOX]] // CHECK: return [[X]] // } // end sil function '[[CAP_NAME]]' // SEMANTIC ARC TODO: This is a place where we have again project_box too early. // CHECK-LABEL: sil hidden @_T08closures16write_to_captureS2iF : $@convention(thin) (Int) -> Int { func write_to_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: store [[X]] to [trivial] [[XBOX_PB]] // CHECK: [[X2BOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[X2BOX_PB:%.*]] = project_box [[X2BOX]] // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*Int // CHECK: copy_addr [[ACCESS]] to [initialization] [[X2BOX_PB]] // CHECK: [[X2BOX_COPY:%.*]] = copy_value [[X2BOX]] // SEMANTIC ARC TODO: This next mark_function_escape should be on a projection from X2BOX_COPY. // CHECK: mark_function_escape [[X2BOX_PB]] var x2 = x func scribble() { x2 = zero } scribble() // CHECK: [[SCRIB:%[0-9]+]] = function_ref @[[SCRIB_NAME:_T08closures16write_to_capture.*]] : $@convention(thin) (@owned { var Int }) -> () // CHECK: apply [[SCRIB]]([[X2BOX_COPY]]) // SEMANTIC ARC TODO: This should load from X2BOX_COPY project. There is an // issue here where after a copy_value, we need to reassign a projection in // some way. // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[X2BOX_PB]] : $*Int // CHECK: [[RET:%[0-9]+]] = load [trivial] [[ACCESS]] // CHECK: destroy_value [[X2BOX]] // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] return x2 } // CHECK: } // end sil function '_T08closures16write_to_captureS2iF' // CHECK: sil private @[[SCRIB_NAME]] // CHECK: bb0([[XBOX:%[0-9]+]] : ${ var Int }): // CHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[XADDR]] : $*Int // CHECK: assign {{%[0-9]+}} to [[ACCESS]] // CHECK: destroy_value [[XBOX]] // CHECK: return // CHECK: } // end sil function '[[SCRIB_NAME]]' // CHECK-LABEL: sil hidden @_T08closures21multiple_closure_refs{{[_0-9a-zA-Z]*}}F func multiple_closure_refs(_ x: Int) -> (() -> Int, () -> Int) { var x = x func cap() -> Int { return x } return (cap, cap) // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_T08closures21multiple_closure_refs.*]] : $@convention(thin) (@owned { var Int }) -> Int // CHECK: [[CAP_CLOSURE_1:%[0-9]+]] = partial_apply [[CAP]] // CHECK: [[CAP:%[0-9]+]] = function_ref @[[CAP_NAME:_T08closures21multiple_closure_refs.*]] : $@convention(thin) (@owned { var Int }) -> Int // CHECK: [[CAP_CLOSURE_2:%[0-9]+]] = partial_apply [[CAP]] // CHECK: [[RET:%[0-9]+]] = tuple ([[CAP_CLOSURE_1]] : {{.*}}, [[CAP_CLOSURE_2]] : {{.*}}) // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_T08closures18capture_local_funcSiycycSiF : $@convention(thin) (Int) -> @owned @callee_owned () -> @owned @callee_owned () -> Int { func capture_local_func(_ x: Int) -> () -> () -> Int { // CHECK: bb0([[ARG:%.*]] : $Int): var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: store [[ARG]] to [trivial] [[XBOX_PB]] func aleph() -> Int { return x } func beth() -> () -> Int { return aleph } // CHECK: [[BETH_REF:%.*]] = function_ref @[[BETH_NAME:_T08closures18capture_local_funcSiycycSiF4bethL_SiycyF]] : $@convention(thin) (@owned { var Int }) -> @owned @callee_owned () -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // SEMANTIC ARC TODO: This is incorrect. This should be a project_box from XBOX_COPY. // CHECK: mark_function_escape [[XBOX_PB]] // CHECK: [[BETH_CLOSURE:%[0-9]+]] = partial_apply [[BETH_REF]]([[XBOX_COPY]]) return beth // CHECK: destroy_value [[XBOX]] // CHECK: return [[BETH_CLOSURE]] } // CHECK: } // end sil function '_T08closures18capture_local_funcSiycycSiF' // CHECK: sil private @[[ALEPH_NAME:_T08closures18capture_local_funcSiycycSiF5alephL_SiyF]] : $@convention(thin) (@owned { var Int }) -> Int { // CHECK: bb0([[XBOX:%[0-9]+]] : ${ var Int }): // CHECK: sil private @[[BETH_NAME]] : $@convention(thin) (@owned { var Int }) -> @owned @callee_owned () -> Int { // CHECK: bb0([[XBOX:%[0-9]+]] : ${ var Int }): // CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]] // CHECK: [[ALEPH_REF:%[0-9]+]] = function_ref @[[ALEPH_NAME]] : $@convention(thin) (@owned { var Int }) -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // SEMANTIC ARC TODO: This should be on a PB from XBOX_COPY. // CHECK: mark_function_escape [[XBOX_PB]] // CHECK: [[ALEPH_CLOSURE:%[0-9]+]] = partial_apply [[ALEPH_REF]]([[XBOX_COPY]]) // CHECK: destroy_value [[XBOX]] // CHECK: return [[ALEPH_CLOSURE]] // CHECK: } // end sil function '[[BETH_NAME]]' // CHECK-LABEL: sil hidden @_T08closures22anon_read_only_capture{{[_0-9a-zA-Z]*}}F func anon_read_only_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[XBOX]] return ({ x })() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_T08closures22anon_read_only_capture[_0-9a-zA-Z]*]] : $@convention(thin) (@inout_aliasable Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]]) // -- cleanup // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil private @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : $*Int): // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int // CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_T08closures21small_closure_capture{{[_0-9a-zA-Z]*}}F func small_closure_capture(_ x: Int) -> Int { var x = x // CHECK: bb0([[X:%[0-9]+]] : $Int): // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[XBOX]] return { x }() // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_T08closures21small_closure_capture[_0-9a-zA-Z]*]] : $@convention(thin) (@inout_aliasable Int) -> Int // -- apply expression // CHECK: [[RET:%[0-9]+]] = apply [[ANON]]([[PB]]) // -- cleanup // CHECK: destroy_value [[XBOX]] // CHECK: return [[RET]] } // CHECK: sil private @[[CLOSURE_NAME]] // CHECK: bb0([[XADDR:%[0-9]+]] : $*Int): // CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[XADDR]] : $*Int // CHECK: [[X:%[0-9]+]] = load [trivial] [[ACCESS]] // CHECK: return [[X]] // CHECK-LABEL: sil hidden @_T08closures35small_closure_capture_with_argument{{[_0-9a-zA-Z]*}}F func small_closure_capture_with_argument(_ x: Int) -> (_ y: Int) -> Int { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Int } return { x + $0 } // -- func expression // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_T08closures35small_closure_capture_with_argument.*]] : $@convention(thin) (Int, @owned { var Int }) -> Int // CHECK: [[XBOX_COPY:%.*]] = copy_value [[XBOX]] // CHECK: [[ANON_CLOSURE_APP:%[0-9]+]] = partial_apply [[ANON]]([[XBOX_COPY]]) // -- return // CHECK: destroy_value [[XBOX]] // CHECK: return [[ANON_CLOSURE_APP]] } // FIXME(integers): the following checks should be updated for the new way + // gets invoked. <rdar://problem/29939484> // XCHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int, @owned { var Int }) -> Int // XCHECK: bb0([[DOLLAR0:%[0-9]+]] : $Int, [[XBOX:%[0-9]+]] : ${ var Int }): // XCHECK: [[XADDR:%[0-9]+]] = project_box [[XBOX]] // XCHECK: [[PLUS:%[0-9]+]] = function_ref @_T0s1poiS2i_SitF{{.*}} // XCHECK: [[LHS:%[0-9]+]] = load [trivial] [[XADDR]] // XCHECK: [[RET:%[0-9]+]] = apply [[PLUS]]([[LHS]], [[DOLLAR0]]) // XCHECK: destroy_value [[XBOX]] // XCHECK: return [[RET]] // CHECK-LABEL: sil hidden @_T08closures24small_closure_no_capture{{[_0-9a-zA-Z]*}}F func small_closure_no_capture() -> (_ y: Int) -> Int { // CHECK: [[ANON:%[0-9]+]] = function_ref @[[CLOSURE_NAME:_T08closures24small_closure_no_captureS2icyFS2icfU_]] : $@convention(thin) (Int) -> Int // CHECK: [[ANON_THICK:%[0-9]+]] = thin_to_thick_function [[ANON]] : ${{.*}} to $@callee_owned (Int) -> Int // CHECK: return [[ANON_THICK]] return { $0 } } // CHECK: sil private @[[CLOSURE_NAME]] : $@convention(thin) (Int) -> Int // CHECK: bb0([[YARG:%[0-9]+]] : $Int): // CHECK-LABEL: sil hidden @_T08closures17uncaptured_locals{{[_0-9a-zA-Z]*}}F : func uncaptured_locals(_ x: Int) -> (Int, Int) { var x = x // -- locals without captures are stack-allocated // CHECK: bb0([[XARG:%[0-9]+]] : $Int): // CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PB:%.*]] = project_box [[XADDR]] // CHECK: store [[XARG]] to [trivial] [[PB]] var y = zero // CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int } return (x, y) } class SomeClass { var x : Int = zero init() { x = { self.x }() // Closing over self. } } // Closures within destructors <rdar://problem/15883734> class SomeGenericClass<T> { deinit { var i: Int = zero // CHECK: [[C1REF:%[0-9]+]] = function_ref @_T08closures16SomeGenericClassCfdSiycfU_ : $@convention(thin) (@inout_aliasable Int) -> Int // CHECK: apply [[C1REF]]([[IBOX:%[0-9]+]]) : $@convention(thin) (@inout_aliasable Int) -> Int var x = { i + zero } () // CHECK: [[C2REF:%[0-9]+]] = function_ref @_T08closures16SomeGenericClassCfdSiycfU0_ : $@convention(thin) () -> Int // CHECK: apply [[C2REF]]() : $@convention(thin) () -> Int var y = { zero } () // CHECK: [[C3REF:%[0-9]+]] = function_ref @_T08closures16SomeGenericClassCfdyycfU1_ : $@convention(thin) <τ_0_0> () -> () // CHECK: apply [[C3REF]]<T>() : $@convention(thin) <τ_0_0> () -> () var z = { _ = T.self } () } // CHECK-LABEL: sil private @_T08closures16SomeGenericClassCfdSiycfU_ : $@convention(thin) (@inout_aliasable Int) -> Int // CHECK-LABEL: sil private @_T08closures16SomeGenericClassCfdSiycfU0_ : $@convention(thin) () -> Int // CHECK-LABEL: sil private @_T08closures16SomeGenericClassCfdyycfU1_ : $@convention(thin) <T> () -> () } // This is basically testing that the constraint system ranking // function conversions as worse than others, and therefore performs // the conversion within closures when possible. class SomeSpecificClass : SomeClass {} func takesSomeClassGenerator(_ fn : () -> SomeClass) {} func generateWithConstant(_ x : SomeSpecificClass) { takesSomeClassGenerator({ x }) } // CHECK-LABEL: sil private @_T08closures20generateWithConstantyAA17SomeSpecificClassCFAA0eG0CycfU_ : $@convention(thin) (@owned SomeSpecificClass) -> @owned SomeClass { // CHECK: bb0([[T0:%.*]] : $SomeSpecificClass): // CHECK: debug_value [[T0]] : $SomeSpecificClass, let, name "x", argno 1 // CHECK: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]] // CHECK: [[T0_COPY_CASTED:%.*]] = upcast [[T0_COPY]] : $SomeSpecificClass to $SomeClass // CHECK: end_borrow [[BORROWED_T0]] from [[T0]] // CHECK: destroy_value [[T0]] // CHECK: return [[T0_COPY_CASTED]] // CHECK: } // end sil function '_T08closures20generateWithConstantyAA17SomeSpecificClassCFAA0eG0CycfU_' // Check the annoying case of capturing 'self' in a derived class 'init' // method. We allocate a mutable box to deal with 'self' potentially being // rebound by super.init, but 'self' is formally immutable and so is captured // by value. <rdar://problem/15599464> class Base {} class SelfCapturedInInit : Base { var foo : () -> SelfCapturedInInit // CHECK-LABEL: sil hidden @_T08closures18SelfCapturedInInitC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit { // CHECK: bb0([[SELF:%.*]] : $SelfCapturedInInit): // // First create our initial value for self. // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var SelfCapturedInInit }, let, name "self" // CHECK: [[UNINIT_SELF:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[UNINIT_SELF]] // CHECK: store [[SELF]] to [init] [[PB_SELF_BOX]] // // Then perform the super init sequence. // CHECK: [[TAKEN_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK: [[UPCAST_TAKEN_SELF:%.*]] = upcast [[TAKEN_SELF]] // CHECK: [[NEW_SELF:%.*]] = apply {{.*}}([[UPCAST_TAKEN_SELF]]) : $@convention(method) (@owned Base) -> @owned Base // CHECK: [[DOWNCAST_NEW_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]] : $Base to $SelfCapturedInInit // CHECK: store [[DOWNCAST_NEW_SELF]] to [init] [[PB_SELF_BOX]] // // Finally put self in the closure. // CHECK: [[BORROWED_SELF:%.*]] = load_borrow [[PB_SELF_BOX]] // CHECK: [[COPIED_SELF:%.*]] = load [copy] [[PB_SELF_BOX]] // CHECK: [[FOO_VALUE:%.*]] = partial_apply {{%.*}}([[COPIED_SELF]]) : $@convention(thin) (@owned SelfCapturedInInit) -> @owned SelfCapturedInInit // CHECK: [[FOO_LOCATION:%.*]] = ref_element_addr [[BORROWED_SELF]] // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[FOO_LOCATION]] : $*@callee_owned () -> @owned SelfCapturedInInit // CHECK: assign [[FOO_VALUE]] to [[ACCESS]] override init() { super.init() foo = { self } } } func takeClosure(_ fn: () -> Int) -> Int { return fn() } class TestCaptureList { var x = zero func testUnowned() { let aLet = self takeClosure { aLet.x } takeClosure { [unowned aLet] in aLet.x } takeClosure { [weak aLet] in aLet!.x } var aVar = self takeClosure { aVar.x } takeClosure { [unowned aVar] in aVar.x } takeClosure { [weak aVar] in aVar!.x } takeClosure { self.x } takeClosure { [unowned self] in self.x } takeClosure { [weak self] in self!.x } takeClosure { [unowned newVal = TestCaptureList()] in newVal.x } takeClosure { [weak newVal = TestCaptureList()] in newVal!.x } } } class ClassWithIntProperty { final var x = 42 } func closeOverLetLValue() { let a : ClassWithIntProperty a = ClassWithIntProperty() takeClosure { a.x } } // The let property needs to be captured into a temporary stack slot so that it // is loadable even though we capture the value. // CHECK-LABEL: sil private @_T08closures18closeOverLetLValueyyFSiycfU_ : $@convention(thin) (@owned ClassWithIntProperty) -> Int { // CHECK: bb0([[ARG:%.*]] : $ClassWithIntProperty): // CHECK: [[TMP_CLASS_ADDR:%.*]] = alloc_stack $ClassWithIntProperty, let, name "a", argno 1 // CHECK: store [[ARG]] to [init] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: [[LOADED_CLASS:%.*]] = load [copy] [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: [[BORROWED_LOADED_CLASS:%.*]] = begin_borrow [[LOADED_CLASS]] // CHECK: [[INT_IN_CLASS_ADDR:%.*]] = ref_element_addr [[BORROWED_LOADED_CLASS]] : $ClassWithIntProperty, #ClassWithIntProperty.x // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[INT_IN_CLASS_ADDR]] : $*Int // CHECK: [[INT_IN_CLASS:%.*]] = load [trivial] [[ACCESS]] : $*Int // CHECK: end_borrow [[BORROWED_LOADED_CLASS]] from [[LOADED_CLASS]] // CHECK: destroy_value [[LOADED_CLASS]] // CHECK: destroy_addr [[TMP_CLASS_ADDR]] : $*ClassWithIntProperty // CHECK: dealloc_stack %1 : $*ClassWithIntProperty // CHECK: return [[INT_IN_CLASS]] // CHECK: } // end sil function '_T08closures18closeOverLetLValueyyFSiycfU_' // Use an external function so inout deshadowing cannot see its body. @_silgen_name("takesNoEscapeClosure") func takesNoEscapeClosure(fn : () -> Int) struct StructWithMutatingMethod { var x = 42 mutating func mutatingMethod() { // This should not capture the refcount of the self shadow. takesNoEscapeClosure { x = 42; return x } } } // Check that the address of self is passed in, but not the refcount pointer. // CHECK-LABEL: sil hidden @_T08closures24StructWithMutatingMethodV08mutatingE0{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*StructWithMutatingMethod): // CHECK: [[CLOSURE:%[0-9]+]] = function_ref @_T08closures24StructWithMutatingMethodV08mutatingE0{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int // CHECK: partial_apply [[CLOSURE]](%0) : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int // Check that the closure body only takes the pointer. // CHECK-LABEL: sil private @_T08closures24StructWithMutatingMethodV08mutatingE0{{.*}} : $@convention(thin) (@inout_aliasable StructWithMutatingMethod) -> Int { // CHECK: bb0(%0 : $*StructWithMutatingMethod): class SuperBase { func boom() {} } class SuperSub : SuperBase { override func boom() {} // CHECK-LABEL: sil hidden @_T08closures8SuperSubC1ayyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_T08closures8SuperSubC1a[_0-9a-zA-Z]*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: apply [[INNER]]([[SELF_COPY]]) // CHECK: } // end sil function '_T08closures8SuperSubC1ayyF' func a() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[CLASS_METHOD:%.*]] = class_method [[BORROWED_ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[BORROWED_ARG]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T08closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' func a1() { self.boom() super.boom() } a1() } // CHECK-LABEL: sil hidden @_T08closures8SuperSubC1byyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_T08closures8SuperSubC1b[_0-9a-zA-Z]*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: = apply [[INNER]]([[SELF_COPY]]) // CHECK: } // end sil function '_T08closures8SuperSubC1byyF' func b() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_T08closures8SuperSubC1b.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: = apply [[INNER]]([[ARG_COPY]]) // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' func b1() { // CHECK: sil private @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[CLASS_METHOD:%.*]] = class_method [[BORROWED_ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[BORROWED_ARG]]) : $@convention(method) (@guaranteed SuperSub) -> () // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_T08closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' func b2() { self.boom() super.boom() } b2() } b1() } // CHECK-LABEL: sil hidden @_T08closures8SuperSubC1cyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_T08closures8SuperSubC1c[_0-9a-zA-Z]*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]]) // CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]] // CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]] // CHECK: apply [[PA_COPY]]() // CHECK: end_borrow [[BORROWED_PA]] from [[PA]] // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '_T08closures8SuperSubC1cyyF' func c() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[CLASS_METHOD:%.*]] = class_method [[BORROWED_ARG]] : $SuperSub, #SuperSub.boom!1 // CHECK: = apply [[CLASS_METHOD]]([[BORROWED_ARG]]) : $@convention(method) (@guaranteed SuperSub) -> () // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%[0-9]+]] = function_ref @_T08closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' let c1 = { () -> Void in self.boom() super.boom() } c1() } // CHECK-LABEL: sil hidden @_T08closures8SuperSubC1dyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_T08closures8SuperSubC1d[_0-9a-zA-Z]*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]]) // CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]] // CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]] // CHECK: apply [[PA_COPY]]() // CHECK: end_borrow [[BORROWED_PA]] from [[PA]] // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '_T08closures8SuperSubC1dyyF' func d() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_T08closures8SuperSubC1d.*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: = apply [[INNER]]([[ARG_COPY]]) // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' let d1 = { () -> Void in // CHECK: sil private @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_T08closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' func d2() { super.boom() } d2() } d1() } // CHECK-LABEL: sil hidden @_T08closures8SuperSubC1eyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME1:_T08closures8SuperSubC1e[_0-9a-zA-Z]*]] : $@convention(thin) // CHECK: = apply [[INNER]]([[SELF_COPY]]) // CHECK: } // end sil function '_T08closures8SuperSubC1eyyF' func e() { // CHECK: sil private @[[INNER_FUNC_NAME1]] : $@convention(thin) // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_NAME2:_T08closures8SuperSubC1e.*]] : $@convention(thin) // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]]) // CHECK: [[BORROWED_PA:%.*]] = begin_borrow [[PA]] // CHECK: [[PA_COPY:%.*]] = copy_value [[BORROWED_PA]] // CHECK: apply [[PA_COPY]]() : $@callee_owned () -> () // CHECK: end_borrow [[BORROWED_PA]] from [[PA]] // CHECK: destroy_value [[PA]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_NAME1]]' func e1() { // CHECK: sil private @[[INNER_FUNC_NAME2]] : $@convention(thin) // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_SUPERCAST:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_T08closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPERCAST]]) // CHECK: destroy_value [[ARG_COPY_SUPERCAST]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: return // CHECK: } // end sil function '[[INNER_FUNC_NAME2]]' let e2 = { super.boom() } e2() } e1() } // CHECK-LABEL: sil hidden @_T08closures8SuperSubC1fyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_T08closures8SuperSubC1fyyFyycfU_]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[SELF_COPY]]) // CHECK: destroy_value [[PA]] // CHECK: } // end sil function '_T08closures8SuperSubC1fyyF' func f() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[TRY_APPLY_AUTOCLOSURE:%.*]] = function_ref @_T0s2qqoixxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error) // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_T08closures8SuperSubC1fyyFyycfU_yyKXKfu_]] : $@convention(thin) (@owned SuperSub) -> @error Error // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]]) // CHECK: [[REABSTRACT_PA:%.*]] = partial_apply {{.*}}([[PA]]) // CHECK: try_apply [[TRY_APPLY_AUTOCLOSURE]]<()>({{.*}}, {{.*}}, [[REABSTRACT_PA]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]] // CHECK: [[NORMAL_BB]]{{.*}} // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' let f1 = { // CHECK: sil private [transparent] @[[INNER_FUNC_2]] // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_T08closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' nil ?? super.boom() } } // CHECK-LABEL: sil hidden @_T08closures8SuperSubC1gyyF : $@convention(method) (@guaranteed SuperSub) -> () { // CHECK: bb0([[SELF:%.*]] : $SuperSub): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_1:_T08closures8SuperSubC1g[_0-9a-zA-Z]*]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: = apply [[INNER]]([[SELF_COPY]]) // CHECK: } // end sil function '_T08closures8SuperSubC1gyyF' func g() { // CHECK: sil private @[[INNER_FUNC_1]] : $@convention(thin) (@owned SuperSub) -> () // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[TRY_APPLY_FUNC:%.*]] = function_ref @_T0s2qqoixxSg_xyKXKtKlF : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error) // CHECK: [[INNER:%.*]] = function_ref @[[INNER_FUNC_2:_T08closures8SuperSubC1g.*]] : $@convention(thin) (@owned SuperSub) -> @error Error // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[PA:%.*]] = partial_apply [[INNER]]([[ARG_COPY]]) // CHECK: [[REABSTRACT_PA:%.*]] = partial_apply {{%.*}}([[PA]]) : $@convention(thin) (@owned @callee_owned () -> @error Error) -> (@out (), @error Error) // CHECK: try_apply [[TRY_APPLY_FUNC]]<()>({{.*}}, {{.*}}, [[REABSTRACT_PA]]) : $@convention(thin) <τ_0_0> (@in Optional<τ_0_0>, @owned @callee_owned () -> (@out τ_0_0, @error Error)) -> (@out τ_0_0, @error Error), normal [[NORMAL_BB:bb1]], error [[ERROR_BB:bb2]] // CHECK: [[NORMAL_BB]]{{.*}} // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_1]]' func g1() { // CHECK: sil private [transparent] @[[INNER_FUNC_2]] : $@convention(thin) (@owned SuperSub) -> @error Error { // CHECK: bb0([[ARG:%.*]] : $SuperSub): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $SuperSub to $SuperBase // CHECK: [[SUPER_METHOD:%.*]] = function_ref @_T08closures9SuperBaseC4boomyyF : $@convention(method) (@guaranteed SuperBase) -> () // CHECK: = apply [[SUPER_METHOD]]([[ARG_COPY_SUPER]]) // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '[[INNER_FUNC_2]]' nil ?? super.boom() } g1() } } // CHECK-LABEL: sil hidden @_T08closures24UnownedSelfNestedCaptureC06nestedE0{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed UnownedSelfNestedCapture) -> () // -- We enter with an assumed strong +1. // CHECK: bb0([[SELF:%.*]] : $UnownedSelfNestedCapture): // CHECK: [[OUTER_SELF_CAPTURE:%.*]] = alloc_box ${ var @sil_unowned UnownedSelfNestedCapture } // CHECK: [[PB:%.*]] = project_box [[OUTER_SELF_CAPTURE]] // -- strong +2 // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[UNOWNED_SELF:%.*]] = ref_to_unowned [[SELF_COPY]] : // -- TODO: A lot of fussy r/r traffic and owned/unowned conversions here. // -- strong +2, unowned +1 // CHECK: unowned_retain [[UNOWNED_SELF]] // CHECK: store [[UNOWNED_SELF]] to [init] [[PB]] // SEMANTIC ARC TODO: This destroy_value should probably be /after/ the load from PB on the next line. // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[UNOWNED_SELF:%.*]] = load [take] [[PB]] // -- strong +2, unowned +1 // CHECK: strong_retain_unowned [[UNOWNED_SELF]] // CHECK: [[SELF:%.*]] = unowned_to_ref [[UNOWNED_SELF]] // CHECK: [[UNOWNED_SELF2:%.*]] = ref_to_unowned [[SELF]] // -- strong +2, unowned +2 // CHECK: unowned_retain [[UNOWNED_SELF2]] // -- strong +1, unowned +2 // CHECK: destroy_value [[SELF]] // -- closure takes unowned ownership // CHECK: [[OUTER_CLOSURE:%.*]] = partial_apply {{%.*}}([[UNOWNED_SELF2]]) // -- call consumes closure // -- strong +1, unowned +1 // CHECK: [[INNER_CLOSURE:%.*]] = apply [[OUTER_CLOSURE]] // CHECK: [[CONSUMED_RESULT:%.*]] = apply [[INNER_CLOSURE]]() // CHECK: destroy_value [[CONSUMED_RESULT]] // -- destroy_values unowned self in box // -- strong +1, unowned +0 // CHECK: destroy_value [[OUTER_SELF_CAPTURE]] // -- strong +0, unowned +0 // CHECK: } // end sil function '_T08closures24UnownedSelfNestedCaptureC06nestedE0{{[_0-9a-zA-Z]*}}F' // -- outer closure // -- strong +0, unowned +1 // CHECK: sil private @[[OUTER_CLOSURE_FUN:_T08closures24UnownedSelfNestedCaptureC06nestedE0yyFACycycfU_]] : $@convention(thin) (@owned @sil_unowned UnownedSelfNestedCapture) -> @owned @callee_owned () -> @owned UnownedSelfNestedCapture { // CHECK: bb0([[CAPTURED_SELF:%.*]] : $@sil_unowned UnownedSelfNestedCapture): // -- strong +0, unowned +2 // CHECK: [[CAPTURED_SELF_COPY:%.*]] = copy_value [[CAPTURED_SELF]] : // -- closure takes ownership of unowned ref // CHECK: [[INNER_CLOSURE:%.*]] = partial_apply {{%.*}}([[CAPTURED_SELF_COPY]]) // -- strong +0, unowned +1 (claimed by closure) // CHECK: destroy_value [[CAPTURED_SELF]] // CHECK: return [[INNER_CLOSURE]] // CHECK: } // end sil function '[[OUTER_CLOSURE_FUN]]' // -- inner closure // -- strong +0, unowned +1 // CHECK: sil private @[[INNER_CLOSURE_FUN:_T08closures24UnownedSelfNestedCaptureC06nestedE0yyFACycycfU_ACycfU_]] : $@convention(thin) (@owned @sil_unowned UnownedSelfNestedCapture) -> @owned UnownedSelfNestedCapture { // CHECK: bb0([[CAPTURED_SELF:%.*]] : $@sil_unowned UnownedSelfNestedCapture): // -- strong +1, unowned +1 // CHECK: strong_retain_unowned [[CAPTURED_SELF:%.*]] : // CHECK: [[SELF:%.*]] = unowned_to_ref [[CAPTURED_SELF]] // -- strong +1, unowned +0 (claimed by return) // CHECK: destroy_value [[CAPTURED_SELF]] // CHECK: return [[SELF]] // CHECK: } // end sil function '[[INNER_CLOSURE_FUN]]' class UnownedSelfNestedCapture { func nestedCapture() { {[unowned self] in { self } }()() } } // Check that capturing 'self' via a 'super' call also captures the generic // signature if the base class is concrete and the derived class is generic class ConcreteBase { func swim() {} } // CHECK-LABEL: sil private @_T08closures14GenericDerivedC4swimyyFyycfU_ : $@convention(thin) <Ocean> (@owned GenericDerived<Ocean>) -> () // CHECK: bb0([[ARG:%.*]] : $GenericDerived<Ocean>): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ARG_COPY_SUPER:%.*]] = upcast [[ARG_COPY]] : $GenericDerived<Ocean> to $ConcreteBase // CHECK: [[METHOD:%.*]] = function_ref @_T08closures12ConcreteBaseC4swimyyF // CHECK: apply [[METHOD]]([[ARG_COPY_SUPER]]) : $@convention(method) (@guaranteed ConcreteBase) -> () // CHECK: destroy_value [[ARG_COPY_SUPER]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_T08closures14GenericDerivedC4swimyyFyycfU_' class GenericDerived<Ocean> : ConcreteBase { override func swim() { withFlotationAid { super.swim() } } func withFlotationAid(_ fn: () -> ()) {} } // Don't crash on this func r25993258_helper(_ fn: (inout Int, Int) -> ()) {} func r25993258() { r25993258_helper { _ in () } } // rdar://29810997 // // Using a let from a closure in an init was causing the type-checker // to produce invalid AST: 'self.fn' was an l-value, but 'self' was already // loaded to make an r-value. This was ultimately because CSApply was // building the member reference correctly in the context of the closure, // where 'fn' is not settable, but CSGen / CSSimplify was processing it // in the general DC of the constraint system, i.e. the init, where // 'fn' *is* settable. func r29810997_helper(_ fn: (Int) -> Int) -> Int { return fn(0) } struct r29810997 { private let fn: (Int) -> Int private var x: Int init(function: @escaping (Int) -> Int) { fn = function x = r29810997_helper { fn($0) } } } // DI will turn this into a direct capture of the specific stored property. // CHECK-LABEL: sil hidden @_T08closures16r29810997_helperS3icF : $@convention(thin) (@owned @callee_owned (Int) -> Int) -> Int
apache-2.0
554a0359813029b206ca511f148ef8ee
48.229141
276
0.58936
3.367206
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieMath/Extension.swift
1
3745
// // MathsExtension.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension Int8: Multiplicative { } extension Int16: Multiplicative { } extension Int32: Multiplicative { } extension Int64: Multiplicative { } extension Int: Multiplicative { } #if !os(macOS) && !targetEnvironment(macCatalyst) @available(iOS 14.0, tvOS 14.0, watchOS 7.0, *) extension Float16: ScalarProtocol { public typealias Scalar = Float16 } #endif extension float16: ScalarProtocol { public typealias Scalar = float16 } extension Float: ScalarProtocol { public typealias Scalar = Float } extension Double: ScalarProtocol { public typealias Scalar = Double } extension CGFloat: ScalarProtocol { public typealias Scalar = CGFloat } extension Complex { @inlinable @inline(__always) public func almostZero(epsilon: Double = Double.ulpOfOne.squareRoot(), reference: Double = 0) -> Bool { return self.real.almostZero(epsilon: epsilon, reference: reference) && self.imag.almostZero(epsilon: epsilon, reference: reference) } @inlinable @inline(__always) public func almostEqual(_ other: Complex, epsilon: Double = Double.ulpOfOne.squareRoot()) -> Bool { return self.real.almostEqual(other.real, epsilon: epsilon) && self.imag.almostEqual(other.imag, epsilon: epsilon) } @inlinable @inline(__always) public func almostEqual(_ other: Complex, epsilon: Double = Double.ulpOfOne.squareRoot(), reference: Double) -> Bool { return self.real.almostEqual(other.real, epsilon: epsilon, reference: reference) && self.imag.almostEqual(other.imag, epsilon: epsilon, reference: reference) } } extension Polynomial { @inlinable @inline(__always) public func almostZero(epsilon: Double = Double.ulpOfOne.squareRoot(), reference: Double = 0) -> Bool { return self.allSatisfy { $0.almostZero(epsilon: epsilon, reference: reference) } } @inlinable @inline(__always) public func almostEqual(_ other: Polynomial, epsilon: Double = Double.ulpOfOne.squareRoot()) -> Bool { return (0..<Swift.max(self.count, other.count)).allSatisfy { self[$0].almostEqual(other[$0], epsilon: epsilon) } } @inlinable @inline(__always) public func almostEqual(_ other: Polynomial, epsilon: Double = Double.ulpOfOne.squareRoot(), reference: Double) -> Bool { return (0..<Swift.max(self.count, other.count)).allSatisfy { self[$0].almostEqual(other[$0], epsilon: epsilon, reference: reference) } } }
mit
08098ab594022f3e014e7d73561acbd5
29.950413
165
0.696128
4.255682
false
false
false
false
material-motion/material-motion-swift
examples/ArcMoveExample.swift
1
3100
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialMotion class ArcMoveExampleViewController: ExampleViewController, TimelineViewDelegate { var runtime: MotionRuntime! var timeline: Timeline! override func viewDidLoad() { super.viewDidLoad() var center = view.center center.x -= 32 center.y -= 32 let blueSquare = createExampleView() blueSquare.frame = .init(x: 0, y: 0, width: blueSquare.bounds.width / 2, height: blueSquare.bounds.height / 2) blueSquare.layer.cornerRadius = blueSquare.bounds.width / 2 view.addSubview(blueSquare) let circle = UIView() circle.frame = CGRect(x: center.x - 100, y: center.y - 200, width: blueSquare.bounds.width, height: blueSquare.bounds.height) circle.layer.cornerRadius = circle.bounds.width / 2 circle.layer.borderColor = UIColor.primaryColor.cgColor circle.layer.borderWidth = 1 view.addSubview(circle) let targetView = UIView(frame: .init(x: center.x, y: center.y, width: blueSquare.bounds.width, height: blueSquare.bounds.height)) targetView.layer.borderWidth = 1 targetView.layer.borderColor = UIColor.secondaryColor.cgColor view.addSubview(targetView) let timelineView = TimelineView() timelineView.delegate = self let size = timelineView.sizeThatFits(view.bounds.size) timelineView.frame = .init(x: 0, y: view.bounds.height - size.height, width: size.width, height: size.height) view.addSubview(timelineView) timeline = Timeline() timelineView.timeline = timeline runtime = MotionRuntime(containerView: view) runtime.shouldVisualizeMotion = true runtime.add(Draggable(), to: circle) runtime.add(Draggable(), to: targetView) let arcMove = ArcMove(tween: .init(timeline: timeline)) arcMove.tween.duration.value = 0.4 runtime.connect(runtime.get(circle.layer).position, to: arcMove.from) runtime.connect(runtime.get(targetView.layer).position, to: arcMove.to) timeline.paused.value = true runtime.add(arcMove, to: blueSquare) } func timelineView(_ timelineView: TimelineView, didChangeSliderValue sliderValue: CGFloat) { timeline.timeOffset.value = sliderValue * 0.4 } func timelineViewDidTogglePause(_ timelineView: TimelineView) { timeline.paused.value = !timeline.paused.value } override func exampleInformation() -> ExampleInfo { return .init(title: type(of: self).catalogBreadcrumbs().last!, instructions: "Move the squares to change the arc movement.") } }
apache-2.0
b87e7c822f328977cb70b36c2b659fd1
34.632184
133
0.733871
4.252401
false
false
false
false