hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
62bc3ae63c2473b0dc3dc9fff676333d4fae5169
520
// // AppDelegate.swift // NSCollectionView-Swift // // Created by AkihiroOrikasa on 2016/12/07. // Copyright © 2016年 Pocosoft. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
19.259259
71
0.721154
e8ce8452bb1885ce92048dea50d2ef2e25f41e8b
1,747
// // RemoteImage.swift // Zeitgeist // // Created by Daniel Eden on 21/12/2020. // Copyright © 2020 Daniel Eden. All rights reserved. // import Foundation #if os(macOS) typealias NativeImage = NSImage #else typealias NativeImage = UIImage #endif import SwiftUI struct RemoteImage: View { private enum LoadState { case loading, success, failure } private class Loader: ObservableObject { var data = Data() var state = LoadState.loading init(url: String) { guard let parsedURL = URL(string: url) else { fatalError("Invalid URL: \(url)") } URLSession.shared.dataTask(with: parsedURL) { data, _, _ in if let data = data, !data.isEmpty { self.data = data self.state = .success } else { self.state = .failure } DispatchQueue.main.async { self.objectWillChange.send() } }.resume() } } @StateObject private var loader: Loader var loading: Image var failure: Image var body: some View { selectImage() .resizable() } init(url: String, loading: Image = Image(systemName: "circle"), failure: Image = Image(systemName: "multiply.circle")) { _loader = StateObject(wrappedValue: Loader(url: url)) self.loading = loading self.failure = failure } private func selectImage() -> Image { switch loader.state { case .loading: return loading case .failure: return failure default: if let image = NativeImage(data: loader.data) { #if os(macOS) return Image(nsImage: image) #else return Image(uiImage: image) #endif } else { return failure } } } }
21.304878
122
0.598741
716813c6776375fedb9c779a651b8744259ea004
3,104
// // ItemList.swift // gemmu // // Created by Akashaka on 09/02/22. // import SwiftUI import NetworkImage public struct ItemList: View { var title: String var releaseDate: String var platforms: [String] var genres: [String] var imageUrl: String var id: Int public init( title: String, releaseDate: String, platforms: [String], genres: [String], imageUrl: String, id: Int ) { self.id = id self.imageUrl = imageUrl self.genres = genres self.platforms = platforms self.releaseDate = releaseDate self.title = title } public var body: some View { ZStack(alignment: .leading) { Color.flatDarkCardBackground HStack { ZStack { if #available(macOS 12.0, *) { if #available(iOS 15.0, *) { NetworkImage(url: URL(string: imageUrl)) { image in image.resizable() } placeholder: { ProgressView() } fallback: { Image(systemName: "photo") } .frame(width: 75, height: 75) .clipped() .background().cornerRadius(10) } else { NetworkImage(url: URL(string: imageUrl)) { image in image.resizable() } placeholder: { ProgressView() } fallback: { Image(systemName: "photo") } .frame(width: 75, height: 75) .clipped() } } else { NetworkImage(url: URL(string: imageUrl)) { image in image.resizable() } placeholder: { ProgressView() } fallback: { Image(systemName: "photo") } .frame(width: 75, height: 75) .clipped() // Fallback on earlier versions } } .frame(width: 70, height: 70, alignment: .center) VStack(alignment: .leading) { Text(title).foregroundColor(.white) .font(.headline) .fontWeight(.bold) .lineLimit(2) .padding(.bottom, 5) Text(releaseDate) .padding(.bottom, 5).foregroundColor(.white) HStack(alignment: .center) { ForEach(platforms, id: \.self) { platform in TagsCard( text: platform, bgColor: .green) } } .padding(.bottom, 5) HStack { ForEach(genres, id: \.self) { genre in TagsCard(text: genre, bgColor: .pink) } } } .padding(.horizontal, 5) } .padding(15) } .clipShape(RoundedRectangle(cornerRadius: 15)) } } struct ItemList_Previews: PreviewProvider { static var previews: some View { let platforms: [String] = ["PS5", "PC"] ItemList( title: "title", releaseDate: "address", platforms: platforms, genres: ["action", "rpg"], imageUrl: Constants.profileImageUrl, id: 3498 ) } }
25.442623
65
0.499678
4a9edd76c8750a9b492824b8a4eef968b43f75eb
77,330
// This file contains parts of Apple's Combine that remain unimplemented in OpenCombine // Please remove the corresponding piece from this file if you implement something, // and complement this file as features are added in Apple's Combine extension Publishers { /// A publisher that receives and combines the latest elements from two publishers. public struct CombineLatest<A, B> : Publisher where A : Publisher, B : Publisher, A.Failure == B.Failure { /// The kind of values published by this publisher. public typealias Output = (A.Output, B.Output) /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public init(_ a: A, _ b: B) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, B.Failure == S.Failure, S.Input == (A.Output, B.Output) } /// A publisher that receives and combines the latest elements from three publishers. public struct CombineLatest3<A, B, C> : Publisher where A : Publisher, B : Publisher, C : Publisher, A.Failure == B.Failure, B.Failure == C.Failure { /// The kind of values published by this publisher. public typealias Output = (A.Output, B.Output, C.Output) /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public init(_ a: A, _ b: B, _ c: C) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, C.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output) } /// A publisher that receives and combines the latest elements from four publishers. public struct CombineLatest4<A, B, C, D> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, A.Failure == B.Failure, B.Failure == C.Failure, C.Failure == D.Failure { /// The kind of values published by this publisher. public typealias Output = (A.Output, B.Output, C.Output, D.Output) /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public let d: D public init(_ a: A, _ b: B, _ c: C, _ d: D) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, D.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output, D.Output) } } extension Publisher { /// Subscribes to an additional publisher and publishes a tuple upon receiving output from either publisher. /// /// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer. /// All upstream publishers need to finish for this publisher to finsh. If an upstream publisher never publishes a value, this publisher never finishes. /// If any of the combined publishers terminates with a failure, this publisher also fails. /// - Parameters: /// - other: Another publisher to combine with this one. /// - Returns: A publisher that receives and combines elements from this and another publisher. public func combineLatest<P>(_ other: P) -> Publishers.CombineLatest<Self, P> where P : Publisher, Self.Failure == P.Failure /// Subscribes to an additional publisher and invokes a closure upon receiving output from either publisher. /// /// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer. /// All upstream publishers need to finish for this publisher to finsh. If an upstream publisher never publishes a value, this publisher never finishes. /// If any of the combined publishers terminates with a failure, this publisher also fails. /// - Parameters: /// - other: Another publisher to combine with this one. /// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish. /// - Returns: A publisher that receives and combines elements from this and another publisher. public func combineLatest<P, T>(_ other: P, _ transform: @escaping (Self.Output, P.Output) -> T) -> Publishers.Map<Publishers.CombineLatest<Self, P>, T> where P : Publisher, Self.Failure == P.Failure /// Subscribes to two additional publishers and publishes a tuple upon receiving output from any of the publishers. /// /// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer. /// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes. /// If any of the combined publishers terminates with a failure, this publisher also fails. /// - Parameters: /// - publisher1: A second publisher to combine with this one. /// - publisher2: A third publisher to combine with this one. /// - Returns: A publisher that receives and combines elements from this publisher and two other publishers. public func combineLatest<P, Q>(_ publisher1: P, _ publisher2: Q) -> Publishers.CombineLatest3<Self, P, Q> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure /// Subscribes to two additional publishers and invokes a closure upon receiving output from any of the publishers. /// /// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer. /// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes. /// If any of the combined publishers terminates with a failure, this publisher also fails. /// - Parameters: /// - publisher1: A second publisher to combine with this one. /// - publisher2: A third publisher to combine with this one. /// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish. /// - Returns: A publisher that receives and combines elements from this publisher and two other publishers. public func combineLatest<P, Q, T>(_ publisher1: P, _ publisher2: Q, _ transform: @escaping (Self.Output, P.Output, Q.Output) -> T) -> Publishers.Map<Publishers.CombineLatest3<Self, P, Q>, T> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure /// Subscribes to three additional publishers and publishes a tuple upon receiving output from any of the publishers. /// /// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer. /// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes. /// If any of the combined publishers terminates with a failure, this publisher also fails. /// - Parameters: /// - publisher1: A second publisher to combine with this one. /// - publisher2: A third publisher to combine with this one. /// - publisher3: A fourth publisher to combine with this one. /// - Returns: A publisher that receives and combines elements from this publisher and three other publishers. public func combineLatest<P, Q, R>(_ publisher1: P, _ publisher2: Q, _ publisher3: R) -> Publishers.CombineLatest4<Self, P, Q, R> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure /// Subscribes to three additional publishers and invokes a closure upon receiving output from any of the publishers. /// /// The combined publisher passes through any requests to *all* upstream publishers. However, it still obeys the demand-fulfilling rule of only sending the request amount downstream. If the demand isn’t `.unlimited`, it drops values from upstream publishers. It implements this by using a buffer size of 1 for each upstream, and holds the most recent value in each buffer. /// All upstream publishers need to finish for this publisher to finish. If an upstream publisher never publishes a value, this publisher never finishes. /// If any of the combined publishers terminates with a failure, this publisher also fails. /// - Parameters: /// - publisher1: A second publisher to combine with this one. /// - publisher2: A third publisher to combine with this one. /// - publisher3: A fourth publisher to combine with this one. /// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish. /// - Returns: A publisher that receives and combines elements from this publisher and three other publishers. public func combineLatest<P, Q, R, T>(_ publisher1: P, _ publisher2: Q, _ publisher3: R, _ transform: @escaping (Self.Output, P.Output, Q.Output, R.Output) -> T) -> Publishers.Map<Publishers.CombineLatest4<Self, P, Q, R>, T> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure } extension Publishers { /// A strategy for collecting received elements. /// /// - byTime: Collect and periodically publish items. /// - byTimeOrCount: Collect and publish items, either periodically or when a buffer reaches its maximum size. public enum TimeGroupingStrategy<Context> where Context : Scheduler { case byTime(Context, Context.SchedulerTimeType.Stride) case byTimeOrCount(Context, Context.SchedulerTimeType.Stride, Int) } /// A publisher that buffers and periodically publishes its items. public struct CollectByTime<Upstream, Context> : Publisher where Upstream : Publisher, Context : Scheduler { /// The kind of values published by this publisher. public typealias Output = [Upstream.Output] /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = Upstream.Failure /// The publisher that this publisher receives elements from. public let upstream: Upstream /// The strategy with which to collect and publish elements. public let strategy: Publishers.TimeGroupingStrategy<Context> /// `Scheduler` options to use for the strategy. public let options: Context.SchedulerOptions? public init(upstream: Upstream, strategy: Publishers.TimeGroupingStrategy<Context>, options: Context.SchedulerOptions?) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, S.Input == [Upstream.Output] } } extension Publisher { /// Collects elements by a given strategy, and emits a single array of the collection. /// /// If the upstream publisher finishes before filling the buffer, this publisher sends an array of all the items it has received. This may be fewer than `count` elements. /// If the upstream publisher fails with an error, this publisher forwards the error to the downstream receiver instead of sending its output. /// Note: When this publisher receives a request for `.max(n)` elements, it requests `.max(count * n)` from the upstream publisher. /// - Parameters: /// - strategy: The strategy with which to collect and publish elements. /// - options: `Scheduler` options to use for the strategy. /// - Returns: A publisher that collects elements by a given strategy, and emits a single array of the collection. public func collect<S>(_ strategy: Publishers.TimeGroupingStrategy<S>, options: S.SchedulerOptions? = nil) -> Publishers.CollectByTime<Self, S> where S : Scheduler } extension Publishers { public struct PrefixUntilOutput<Upstream, Other> : Publisher where Upstream : Publisher, Other : Publisher { /// The kind of values published by this publisher. public typealias Output = Upstream.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = Upstream.Failure /// The publisher from which this publisher receives elements. public let upstream: Upstream /// Another publisher, whose first output causes this publisher to finish. public let other: Other public init(upstream: Upstream, other: Other) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, Upstream.Output == S.Input } } extension Publisher { /// Republishes elements until another publisher emits an element. /// /// After the second publisher publishes an element, the publisher returned by this method finishes. /// /// - Parameter publisher: A second publisher. /// - Returns: A publisher that republishes elements until the second publisher publishes an element. public func prefix<P>(untilOutputFrom publisher: P) -> Publishers.PrefixUntilOutput<Self, P> where P : Publisher } extension Publishers { /// A publisher created by applying the merge function to two upstream publishers. public struct Merge<A, B> : Publisher where A : Publisher, B : Publisher, A.Failure == B.Failure, A.Output == B.Output { /// The kind of values published by this publisher. public typealias Output = A.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public init(_ a: A, _ b: B) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, B.Failure == S.Failure, B.Output == S.Input public func merge<P>(with other: P) -> Publishers.Merge3<A, B, P> where P : Publisher, B.Failure == P.Failure, B.Output == P.Output public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge4<A, B, Z, Y> where Z : Publisher, Y : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output public func merge<Z, Y, X>(with z: Z, _ y: Y, _ x: X) -> Publishers.Merge5<A, B, Z, Y, X> where Z : Publisher, Y : Publisher, X : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output public func merge<Z, Y, X, W>(with z: Z, _ y: Y, _ x: X, _ w: W) -> Publishers.Merge6<A, B, Z, Y, X, W> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output public func merge<Z, Y, X, W, V>(with z: Z, _ y: Y, _ x: X, _ w: W, _ v: V) -> Publishers.Merge7<A, B, Z, Y, X, W, V> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, V : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output, W.Failure == V.Failure, W.Output == V.Output public func merge<Z, Y, X, W, V, U>(with z: Z, _ y: Y, _ x: X, _ w: W, _ v: V, _ u: U) -> Publishers.Merge8<A, B, Z, Y, X, W, V, U> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, V : Publisher, U : Publisher, B.Failure == Z.Failure, B.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output, W.Failure == V.Failure, W.Output == V.Output, V.Failure == U.Failure, V.Output == U.Output } /// A publisher created by applying the merge function to three upstream publishers. public struct Merge3<A, B, C> : Publisher where A : Publisher, B : Publisher, C : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output { /// The kind of values published by this publisher. public typealias Output = A.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public init(_ a: A, _ b: B, _ c: C) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, C.Failure == S.Failure, C.Output == S.Input public func merge<P>(with other: P) -> Publishers.Merge4<A, B, C, P> where P : Publisher, C.Failure == P.Failure, C.Output == P.Output public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge5<A, B, C, Z, Y> where Z : Publisher, Y : Publisher, C.Failure == Z.Failure, C.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output public func merge<Z, Y, X>(with z: Z, _ y: Y, _ x: X) -> Publishers.Merge6<A, B, C, Z, Y, X> where Z : Publisher, Y : Publisher, X : Publisher, C.Failure == Z.Failure, C.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output public func merge<Z, Y, X, W>(with z: Z, _ y: Y, _ x: X, _ w: W) -> Publishers.Merge7<A, B, C, Z, Y, X, W> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, C.Failure == Z.Failure, C.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output public func merge<Z, Y, X, W, V>(with z: Z, _ y: Y, _ x: X, _ w: W, _ v: V) -> Publishers.Merge8<A, B, C, Z, Y, X, W, V> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, V : Publisher, C.Failure == Z.Failure, C.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output, W.Failure == V.Failure, W.Output == V.Output } /// A publisher created by applying the merge function to four upstream publishers. public struct Merge4<A, B, C, D> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output { /// The kind of values published by this publisher. public typealias Output = A.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public let d: D public init(_ a: A, _ b: B, _ c: C, _ d: D) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, D.Failure == S.Failure, D.Output == S.Input public func merge<P>(with other: P) -> Publishers.Merge5<A, B, C, D, P> where P : Publisher, D.Failure == P.Failure, D.Output == P.Output public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge6<A, B, C, D, Z, Y> where Z : Publisher, Y : Publisher, D.Failure == Z.Failure, D.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output public func merge<Z, Y, X>(with z: Z, _ y: Y, _ x: X) -> Publishers.Merge7<A, B, C, D, Z, Y, X> where Z : Publisher, Y : Publisher, X : Publisher, D.Failure == Z.Failure, D.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output public func merge<Z, Y, X, W>(with z: Z, _ y: Y, _ x: X, _ w: W) -> Publishers.Merge8<A, B, C, D, Z, Y, X, W> where Z : Publisher, Y : Publisher, X : Publisher, W : Publisher, D.Failure == Z.Failure, D.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output, X.Failure == W.Failure, X.Output == W.Output } /// A publisher created by applying the merge function to five upstream publishers. public struct Merge5<A, B, C, D, E> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, E : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output { /// The kind of values published by this publisher. public typealias Output = A.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public let d: D public let e: E public init(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, E.Failure == S.Failure, E.Output == S.Input public func merge<P>(with other: P) -> Publishers.Merge6<A, B, C, D, E, P> where P : Publisher, E.Failure == P.Failure, E.Output == P.Output public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge7<A, B, C, D, E, Z, Y> where Z : Publisher, Y : Publisher, E.Failure == Z.Failure, E.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output public func merge<Z, Y, X>(with z: Z, _ y: Y, _ x: X) -> Publishers.Merge8<A, B, C, D, E, Z, Y, X> where Z : Publisher, Y : Publisher, X : Publisher, E.Failure == Z.Failure, E.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output, Y.Failure == X.Failure, Y.Output == X.Output } /// A publisher created by applying the merge function to six upstream publishers. public struct Merge6<A, B, C, D, E, F> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output { /// The kind of values published by this publisher. public typealias Output = A.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public let d: D public let e: E public let f: F public init(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, F.Failure == S.Failure, F.Output == S.Input public func merge<P>(with other: P) -> Publishers.Merge7<A, B, C, D, E, F, P> where P : Publisher, F.Failure == P.Failure, F.Output == P.Output public func merge<Z, Y>(with z: Z, _ y: Y) -> Publishers.Merge8<A, B, C, D, E, F, Z, Y> where Z : Publisher, Y : Publisher, F.Failure == Z.Failure, F.Output == Z.Output, Z.Failure == Y.Failure, Z.Output == Y.Output } /// A publisher created by applying the merge function to seven upstream publishers. public struct Merge7<A, B, C, D, E, F, G> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output { /// The kind of values published by this publisher. public typealias Output = A.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public let d: D public let e: E public let f: F public let g: G public init(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, G.Failure == S.Failure, G.Output == S.Input public func merge<P>(with other: P) -> Publishers.Merge8<A, B, C, D, E, F, G, P> where P : Publisher, G.Failure == P.Failure, G.Output == P.Output } /// A publisher created by applying the merge function to eight upstream publishers. public struct Merge8<A, B, C, D, E, F, G, H> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, H : Publisher, A.Failure == B.Failure, A.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output, G.Failure == H.Failure, G.Output == H.Output { /// The kind of values published by this publisher. public typealias Output = A.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public let d: D public let e: E public let f: F public let g: G public let h: H public init(_ a: A, _ b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, H.Failure == S.Failure, H.Output == S.Input } public struct MergeMany<Upstream> : Publisher where Upstream : Publisher { /// The kind of values published by this publisher. public typealias Output = Upstream.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = Upstream.Failure public let publishers: [Upstream] public init(_ upstream: Upstream...) public init<S>(_ upstream: S) where Upstream == S.Element, S : Sequence /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, Upstream.Output == S.Input public func merge(with other: Upstream) -> Publishers.MergeMany<Upstream> } } extension Publisher { /// Combines elements from this publisher with those from another publisher, delivering an interleaved sequence of elements. /// /// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error. /// - Parameter other: Another publisher. /// - Returns: A publisher that emits an event when either upstream publisher emits an event. public func merge<P>(with other: P) -> Publishers.Merge<Self, P> where P : Publisher, Self.Failure == P.Failure, Self.Output == P.Output /// Combines elements from this publisher with those from two other publishers, delivering an interleaved sequence of elements. /// /// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error. /// /// - Parameters: /// - b: A second publisher. /// - c: A third publisher. /// - Returns: A publisher that emits an event when any upstream publisher emits /// an event. public func merge<B, C>(with b: B, _ c: C) -> Publishers.Merge3<Self, B, C> where B : Publisher, C : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output /// Combines elements from this publisher with those from three other publishers, delivering /// an interleaved sequence of elements. /// /// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error. /// /// - Parameters: /// - b: A second publisher. /// - c: A third publisher. /// - d: A fourth publisher. /// - Returns: A publisher that emits an event when any upstream publisher emits an event. public func merge<B, C, D>(with b: B, _ c: C, _ d: D) -> Publishers.Merge4<Self, B, C, D> where B : Publisher, C : Publisher, D : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output /// Combines elements from this publisher with those from four other publishers, delivering an interleaved sequence of elements. /// /// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error. /// /// - Parameters: /// - b: A second publisher. /// - c: A third publisher. /// - d: A fourth publisher. /// - e: A fifth publisher. /// - Returns: A publisher that emits an event when any upstream publisher emits an event. public func merge<B, C, D, E>(with b: B, _ c: C, _ d: D, _ e: E) -> Publishers.Merge5<Self, B, C, D, E> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output /// Combines elements from this publisher with those from five other publishers, delivering an interleaved sequence of elements. /// /// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error. /// /// - Parameters: /// - b: A second publisher. /// - c: A third publisher. /// - d: A fourth publisher. /// - e: A fifth publisher. /// - f: A sixth publisher. /// - Returns: A publisher that emits an event when any upstream publisher emits an event. public func merge<B, C, D, E, F>(with b: B, _ c: C, _ d: D, _ e: E, _ f: F) -> Publishers.Merge6<Self, B, C, D, E, F> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output /// Combines elements from this publisher with those from six other publishers, delivering an interleaved sequence of elements. /// /// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error. /// /// - Parameters: /// - b: A second publisher. /// - c: A third publisher. /// - d: A fourth publisher. /// - e: A fifth publisher. /// - f: A sixth publisher. /// - g: A seventh publisher. /// - Returns: A publisher that emits an event when any upstream publisher emits an event. public func merge<B, C, D, E, F, G>(with b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G) -> Publishers.Merge7<Self, B, C, D, E, F, G> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output /// Combines elements from this publisher with those from seven other publishers, delivering an interleaved sequence of elements. /// /// The merged publisher continues to emit elements until all upstream publishers finish. If an upstream publisher produces an error, the merged publisher fails with that error. /// /// - Parameters: /// - b: A second publisher. /// - c: A third publisher. /// - d: A fourth publisher. /// - e: A fifth publisher. /// - f: A sixth publisher. /// - g: A seventh publisher. /// - h: An eighth publisher. /// - Returns: A publisher that emits an event when any upstream publisher emits an event. public func merge<B, C, D, E, F, G, H>(with b: B, _ c: C, _ d: D, _ e: E, _ f: F, _ g: G, _ h: H) -> Publishers.Merge8<Self, B, C, D, E, F, G, H> where B : Publisher, C : Publisher, D : Publisher, E : Publisher, F : Publisher, G : Publisher, H : Publisher, Self.Failure == B.Failure, Self.Output == B.Output, B.Failure == C.Failure, B.Output == C.Output, C.Failure == D.Failure, C.Output == D.Output, D.Failure == E.Failure, D.Output == E.Output, E.Failure == F.Failure, E.Output == F.Output, F.Failure == G.Failure, F.Output == G.Output, G.Failure == H.Failure, G.Output == H.Output /// Combines elements from this publisher with those from another publisher of the same type, delivering an interleaved sequence of elements. /// /// - Parameter other: Another publisher of this publisher's type. /// - Returns: A publisher that emits an event when either upstream publisher emits /// an event. public func merge(with other: Self) -> Publishers.MergeMany<Self> } extension Publishers { /// A publisher that “flattens” nested publishers. /// /// Given a publisher that publishes Publishers, the `SwitchToLatest` publisher produces a sequence of events from only the most recent one. /// For example, given the type `Publisher<Publisher<Data, NSError>, Never>`, calling `switchToLatest()` will result in the type `Publisher<Data, NSError>`. The downstream subscriber sees a continuous stream of values even though they may be coming from different upstream publishers. public struct SwitchToLatest<P, Upstream> : Publisher where P : Publisher, P == Upstream.Output, Upstream : Publisher, P.Failure == Upstream.Failure { /// The kind of values published by this publisher. public typealias Output = P.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = P.Failure /// The publisher from which this publisher receives elements. public let upstream: Upstream /// Creates a publisher that “flattens” nested publishers. /// /// - Parameter upstream: The publisher from which this publisher receives elements. public init(upstream: Upstream) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, P.Output == S.Input, Upstream.Failure == S.Failure } } extension Publisher where Self.Failure == Self.Output.Failure, Self.Output : Publisher { /// Flattens the stream of events from multiple upstream publishers to appear as if they were coming from a single stream of events. /// /// This operator switches the inner publisher as new ones arrive but keeps the outer one constant for downstream subscribers. /// For example, given the type `Publisher<Publisher<Data, NSError>, Never>`, calling `switchToLatest()` will result in the type `Publisher<Data, NSError>`. The downstream subscriber sees a continuous stream of values even though they may be coming from different upstream publishers. public func switchToLatest() -> Publishers.SwitchToLatest<Self.Output, Self> } extension Publishers { /// A publisher that attempts to recreate its subscription to a failed upstream publisher. public struct Retry<Upstream> : Publisher where Upstream : Publisher { /// The kind of values published by this publisher. public typealias Output = Upstream.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = Upstream.Failure /// The publisher from which this publisher receives elements. public let upstream: Upstream /// The maximum number of retry attempts to perform. /// /// If `nil`, this publisher attempts to reconnect with the upstream publisher an unlimited number of times. public let retries: Int? /// Creates a publisher that attempts to recreate its subscription to a failed upstream publisher. /// /// - Parameters: /// - upstream: The publisher from which this publisher receives its elements. /// - retries: The maximum number of retry attempts to perform. If `nil`, this publisher attempts to reconnect with the upstream publisher an unlimited number of times. public init(upstream: Upstream, retries: Int?) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, Upstream.Output == S.Input } } extension Publisher { /// Attempts to recreate a failed subscription with the upstream publisher using a specified number of attempts to establish the connection. /// /// After exceeding the specified number of retries, the publisher passes the failure to the downstream receiver. /// - Parameter retries: The number of times to attempt to recreate the subscription. /// - Returns: A publisher that attempts to recreate its subscription to a failed upstream publisher. public func retry(_ retries: Int) -> Publishers.Retry<Self> } extension Publisher { /// Attempts to recreate a failed subscription with the upstream publisher using a specified number of attempts to establish the connection. /// /// After exceeding the specified number of retries, the publisher passes the failure to the downstream receiver. /// - Parameter retries: The number of times to attempt to recreate the subscription. /// - Returns: A publisher that attempts to recreate its subscription to a failed upstream publisher. public func retry(_ retries: Int) -> Publishers.Retry<Self> } extension Publishers { /// A publisher that publishes either the most-recent or first element published by the upstream publisher in a specified time interval. public struct Throttle<Upstream, Context> : Publisher where Upstream : Publisher, Context : Scheduler { /// The kind of values published by this publisher. public typealias Output = Upstream.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = Upstream.Failure /// The publisher from which this publisher receives elements. public let upstream: Upstream /// The interval in which to find and emit the most recent element. public let interval: Context.SchedulerTimeType.Stride /// The scheduler on which to publish elements. public let scheduler: Context /// A Boolean value indicating whether to publish the most recent element. /// /// If `false`, the publisher emits the first element received during the interval. public let latest: Bool public init(upstream: Upstream, interval: Context.SchedulerTimeType.Stride, scheduler: Context, latest: Bool) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, Upstream.Output == S.Input } } extension Publisher { /// Publishes either the most-recent or first element published by the upstream publisher in the specified time interval. /// /// - Parameters: /// - interval: The interval at which to find and emit the most recent element, expressed in the time system of the scheduler. /// - scheduler: The scheduler on which to publish elements. /// - latest: A Boolean value that indicates whether to publish the most recent element. If `false`, the publisher emits the first element received during the interval. /// - Returns: A publisher that emits either the most-recent or first element received during the specified interval. public func throttle<S>(for interval: S.SchedulerTimeType.Stride, scheduler: S, latest: Bool) -> Publishers.Throttle<Self, S> where S : Scheduler } extension Publishers { /// A publisher that publishes elements only after a specified time interval elapses between events. public struct Debounce<Upstream, Context> : Publisher where Upstream : Publisher, Context : Scheduler { /// The kind of values published by this publisher. public typealias Output = Upstream.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = Upstream.Failure /// The publisher from which this publisher receives elements. public let upstream: Upstream /// The amount of time the publisher should wait before publishing an element. public let dueTime: Context.SchedulerTimeType.Stride /// The scheduler on which this publisher delivers elements. public let scheduler: Context /// Scheduler options that customize this publisher’s delivery of elements. public let options: Context.SchedulerOptions? public init(upstream: Upstream, dueTime: Context.SchedulerTimeType.Stride, scheduler: Context, options: Context.SchedulerOptions?) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, Upstream.Output == S.Input } } extension Publisher { /// Publishes elements only after a specified time interval elapses between events. /// /// Use this operator when you want to wait for a pause in the delivery of events from the upstream publisher. For example, call `debounce` on the publisher from a text field to only receive elements when the user pauses or stops typing. When they start typing again, the `debounce` holds event delivery until the next pause. /// - Parameters: /// - dueTime: The time the publisher should wait before publishing an element. /// - scheduler: The scheduler on which this publisher delivers elements /// - options: Scheduler options that customize this publisher’s delivery of elements. /// - Returns: A publisher that publishes events only after a specified time elapses. public func debounce<S>(for dueTime: S.SchedulerTimeType.Stride, scheduler: S, options: S.SchedulerOptions? = nil) -> Publishers.Debounce<Self, S> where S : Scheduler } extension Publishers { public struct Timeout<Upstream, Context> : Publisher where Upstream : Publisher, Context : Scheduler { /// The kind of values published by this publisher. public typealias Output = Upstream.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = Upstream.Failure public let upstream: Upstream public let interval: Context.SchedulerTimeType.Stride public let scheduler: Context public let options: Context.SchedulerOptions? public let customError: (() -> Upstream.Failure)? public init(upstream: Upstream, interval: Context.SchedulerTimeType.Stride, scheduler: Context, options: Context.SchedulerOptions?, customError: (() -> Publishers.Timeout<Upstream, Context>.Failure)?) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, Upstream.Failure == S.Failure, Upstream.Output == S.Input } } extension Publisher { /// Terminates publishing if the upstream publisher exceeds the specified time interval without producing an element. /// /// - Parameters: /// - interval: The maximum time interval the publisher can go without emitting an element, expressed in the time system of the scheduler. /// - scheduler: The scheduler to deliver events on. /// - options: Scheduler options that customize the delivery of elements. /// - customError: A closure that executes if the publisher times out. The publisher sends the failure returned by this closure to the subscriber as the reason for termination. /// - Returns: A publisher that terminates if the specified interval elapses with no events received from the upstream publisher. public func timeout<S>(_ interval: S.SchedulerTimeType.Stride, scheduler: S, options: S.SchedulerOptions? = nil, customError: (() -> Self.Failure)? = nil) -> Publishers.Timeout<Self, S> where S : Scheduler } extension Publishers { /// A publisher created by applying the zip function to two upstream publishers. public struct Zip<A, B> : Publisher where A : Publisher, B : Publisher, A.Failure == B.Failure { /// The kind of values published by this publisher. public typealias Output = (A.Output, B.Output) /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public init(_ a: A, _ b: B) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, B.Failure == S.Failure, S.Input == (A.Output, B.Output) } /// A publisher created by applying the zip function to three upstream publishers. public struct Zip3<A, B, C> : Publisher where A : Publisher, B : Publisher, C : Publisher, A.Failure == B.Failure, B.Failure == C.Failure { /// The kind of values published by this publisher. public typealias Output = (A.Output, B.Output, C.Output) /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public init(_ a: A, _ b: B, _ c: C) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, C.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output) } /// A publisher created by applying the zip function to four upstream publishers. public struct Zip4<A, B, C, D> : Publisher where A : Publisher, B : Publisher, C : Publisher, D : Publisher, A.Failure == B.Failure, B.Failure == C.Failure, C.Failure == D.Failure { /// The kind of values published by this publisher. public typealias Output = (A.Output, B.Output, C.Output, D.Output) /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = A.Failure public let a: A public let b: B public let c: C public let d: D public init(_ a: A, _ b: B, _ c: C, _ d: D) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, D.Failure == S.Failure, S.Input == (A.Output, B.Output, C.Output, D.Output) } } extension Publisher { /// Combine elements from another publisher and deliver pairs of elements as tuples. /// /// The returned publisher waits until both publishers have emitted an event, then delivers the oldest unconsumed event from each publisher together as a tuple to the subscriber. /// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits event `c`, the zip publisher emits the tuple `(a, c)`. It won’t emit a tuple with event `b` until `P2` emits another event. /// If either upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same. /// /// - Parameter other: Another publisher. /// - Returns: A publisher that emits pairs of elements from the upstream publishers as tuples. public func zip<P>(_ other: P) -> Publishers.Zip<Self, P> where P : Publisher, Self.Failure == P.Failure /// Combine elements from another publisher and deliver a transformed output. /// /// The returned publisher waits until both publishers have emitted an event, then delivers the oldest unconsumed event from each publisher together as a tuple to the subscriber. /// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits event `c`, the zip publisher emits the tuple `(a, c)`. It won’t emit a tuple with event `b` until `P2` emits another event. /// If either upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same. /// /// - Parameter other: Another publisher. /// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish. /// - Returns: A publisher that emits pairs of elements from the upstream publishers as tuples. public func zip<P, T>(_ other: P, _ transform: @escaping (Self.Output, P.Output) -> T) -> Publishers.Map<Publishers.Zip<Self, P>, T> where P : Publisher, Self.Failure == P.Failure /// Combine elements from two other publishers and deliver groups of elements as tuples. /// /// The returned publisher waits until all three publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber. /// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the event `e`, the zip publisher emits the tuple `(a, c, e)`. It won’t emit a tuple with elements `b` or `d` until `P3` emits another event. /// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same. /// /// - Parameters: /// - publisher1: A second publisher. /// - publisher2: A third publisher. /// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples. public func zip<P, Q>(_ publisher1: P, _ publisher2: Q) -> Publishers.Zip3<Self, P, Q> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure /// Combine elements from two other publishers and deliver a transformed output. /// /// The returned publisher waits until all three publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber. /// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the event `e`, the zip publisher emits the tuple `(a, c, e)`. It won’t emit a tuple with elements `b` or `d` until `P3` emits another event. /// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same. /// /// - Parameters: /// - publisher1: A second publisher. /// - publisher2: A third publisher. /// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish. /// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples. public func zip<P, Q, T>(_ publisher1: P, _ publisher2: Q, _ transform: @escaping (Self.Output, P.Output, Q.Output) -> T) -> Publishers.Map<Publishers.Zip3<Self, P, Q>, T> where P : Publisher, Q : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure /// Combine elements from three other publishers and deliver groups of elements as tuples. /// /// The returned publisher waits until all four publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber. /// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the elements `e` and `f`, and publisher `P4` emits the event `g`, the zip publisher emits the tuple `(a, c, e, g)`. It won’t emit a tuple with elements `b`, `d`, or `f` until `P4` emits another event. /// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same. /// /// - Parameters: /// - publisher1: A second publisher. /// - publisher2: A third publisher. /// - publisher3: A fourth publisher. /// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples. public func zip<P, Q, R>(_ publisher1: P, _ publisher2: Q, _ publisher3: R) -> Publishers.Zip4<Self, P, Q, R> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure /// Combine elements from three other publishers and deliver a transformed output. /// /// The returned publisher waits until all four publishers have emitted an event, then delivers the oldest unconsumed event from each publisher as a tuple to the subscriber. /// For example, if publisher `P1` emits elements `a` and `b`, and publisher `P2` emits elements `c` and `d`, and publisher `P3` emits the elements `e` and `f`, and publisher `P4` emits the event `g`, the zip publisher emits the tuple `(a, c, e, g)`. It won’t emit a tuple with elements `b`, `d`, or `f` until `P4` emits another event. /// If any upstream publisher finishes successfuly or fails with an error, the zipped publisher does the same. /// /// - Parameters: /// - publisher1: A second publisher. /// - publisher2: A third publisher. /// - publisher3: A fourth publisher. /// - transform: A closure that receives the most recent value from each publisher and returns a new value to publish. /// - Returns: A publisher that emits groups of elements from the upstream publishers as tuples. public func zip<P, Q, R, T>(_ publisher1: P, _ publisher2: Q, _ publisher3: R, _ transform: @escaping (Self.Output, P.Output, Q.Output, R.Output) -> T) -> Publishers.Map<Publishers.Zip4<Self, P, Q, R>, T> where P : Publisher, Q : Publisher, R : Publisher, Self.Failure == P.Failure, P.Failure == Q.Failure, Q.Failure == R.Failure } extension Publishers { /// A publisher that handles errors from an upstream publisher by replacing the failed publisher with another publisher. public struct Catch<Upstream, NewPublisher> : Publisher where Upstream : Publisher, NewPublisher : Publisher, Upstream.Output == NewPublisher.Output { /// The kind of values published by this publisher. public typealias Output = Upstream.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = NewPublisher.Failure /// The publisher that this publisher receives elements from. public let upstream: Upstream /// A closure that accepts the upstream failure as input and returns a publisher to replace the upstream publisher. public let handler: (Upstream.Failure) -> NewPublisher /// Creates a publisher that handles errors from an upstream publisher by replacing the failed publisher with another publisher. /// /// - Parameters: /// - upstream: The publisher that this publisher receives elements from. /// - handler: A closure that accepts the upstream failure as input and returns a publisher to replace the upstream publisher. public init(upstream: Upstream, handler: @escaping (Upstream.Failure) -> NewPublisher) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, NewPublisher.Failure == S.Failure, NewPublisher.Output == S.Input } /// A publisher that handles errors from an upstream publisher by replacing the failed publisher with another publisher or optionally producing a new error. public struct TryCatch<Upstream, NewPublisher> : Publisher where Upstream : Publisher, NewPublisher : Publisher, Upstream.Output == NewPublisher.Output { /// The kind of values published by this publisher. public typealias Output = Upstream.Output /// The kind of errors this publisher might publish. /// /// Use `Never` if this `Publisher` does not publish errors. public typealias Failure = Error public let upstream: Upstream public let handler: (Upstream.Failure) throws -> NewPublisher public init(upstream: Upstream, handler: @escaping (Upstream.Failure) throws -> NewPublisher) /// This function is called to attach the specified `Subscriber` to this `Publisher` by `subscribe(_:)` /// /// - SeeAlso: `subscribe(_:)` /// - Parameters: /// - subscriber: The subscriber to attach to this `Publisher`. /// once attached it can begin to receive values. public func receive<S>(subscriber: S) where S : Subscriber, NewPublisher.Output == S.Input, S.Failure == Publishers.TryCatch<Upstream, NewPublisher>.Failure } } extension Publisher { /// Handles errors from an upstream publisher by replacing it with another publisher. /// /// The following example replaces any error from the upstream publisher and replaces the upstream with a `Just` publisher. This continues the stream by publishing a single value and completing normally. /// ``` /// enum SimpleError: Error { case error } /// let errorPublisher = (0..<10).publisher.tryMap { v -> Int in /// if v < 5 { /// return v /// } else { /// throw SimpleError.error /// } /// } /// /// let noErrorPublisher = errorPublisher.catch { _ in /// return Just(100) /// } /// ``` /// Backpressure note: This publisher passes through `request` and `cancel` to the upstream. After receiving an error, the publisher sends sends any unfulfilled demand to the new `Publisher`. /// - Parameter handler: A closure that accepts the upstream failure as input and returns a publisher to replace the upstream publisher. /// - Returns: A publisher that handles errors from an upstream publisher by replacing the failed publisher with another publisher. public func `catch`<P>(_ handler: @escaping (Self.Failure) -> P) -> Publishers.Catch<Self, P> where P : Publisher, Self.Output == P.Output /// Handles errors from an upstream publisher by either replacing it with another publisher or `throw`ing a new error. /// /// - Parameter handler: A `throw`ing closure that accepts the upstream failure as input and returns a publisher to replace the upstream publisher or if an error is thrown will send the error downstream. /// - Returns: A publisher that handles errors from an upstream publisher by replacing the failed publisher with another publisher. public func tryCatch<P>(_ handler: @escaping (Self.Failure) throws -> P) -> Publishers.TryCatch<Self, P> where P : Publisher, Self.Output == P.Output } extension Publishers.CombineLatest : Equatable where A : Equatable, B : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A combineLatest publisher to compare for equality. /// - rhs: Another combineLatest publisher to compare for equality. /// - Returns: `true` if the corresponding upstream publishers of each combineLatest publisher are equal, `false` otherwise. public static func == (lhs: Publishers.CombineLatest<A, B>, rhs: Publishers.CombineLatest<A, B>) -> Bool } extension Publishers.CombineLatest3 : Equatable where A : Equatable, B : Equatable, C : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Publishers.CombineLatest3<A, B, C>, rhs: Publishers.CombineLatest3<A, B, C>) -> Bool } extension Publishers.CombineLatest4 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Publishers.CombineLatest4<A, B, C, D>, rhs: Publishers.CombineLatest4<A, B, C, D>) -> Bool } extension Publishers.Merge : Equatable where A : Equatable, B : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A merging publisher to compare for equality. /// - rhs: Another merging publisher to compare for equality.. /// - Returns: `true` if the two merging - rhs: Another merging publisher to compare for equality. public static func == (lhs: Publishers.Merge<A, B>, rhs: Publishers.Merge<A, B>) -> Bool } extension Publishers.Merge3 : Equatable where A : Equatable, B : Equatable, C : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A merging publisher to compare for equality. /// - rhs: Another merging publisher to compare for equality. /// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise. public static func == (lhs: Publishers.Merge3<A, B, C>, rhs: Publishers.Merge3<A, B, C>) -> Bool } extension Publishers.Merge4 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A merging publisher to compare for equality. /// - rhs: Another merging publisher to compare for equality. /// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise. public static func == (lhs: Publishers.Merge4<A, B, C, D>, rhs: Publishers.Merge4<A, B, C, D>) -> Bool } extension Publishers.Merge5 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable, E : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A merging publisher to compare for equality. /// - rhs: Another merging publisher to compare for equality. /// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise. public static func == (lhs: Publishers.Merge5<A, B, C, D, E>, rhs: Publishers.Merge5<A, B, C, D, E>) -> Bool } extension Publishers.Merge6 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable, E : Equatable, F : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A merging publisher to compare for equality. /// - rhs: Another merging publisher to compare for equality. /// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise. public static func == (lhs: Publishers.Merge6<A, B, C, D, E, F>, rhs: Publishers.Merge6<A, B, C, D, E, F>) -> Bool } extension Publishers.Merge7 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable, E : Equatable, F : Equatable, G : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A merging publisher to compare for equality. /// - rhs: Another merging publisher to compare for equality. /// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise. public static func == (lhs: Publishers.Merge7<A, B, C, D, E, F, G>, rhs: Publishers.Merge7<A, B, C, D, E, F, G>) -> Bool } extension Publishers.Merge8 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable, E : Equatable, F : Equatable, G : Equatable, H : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A merging publisher to compare for equality. /// - rhs: Another merging publisher to compare for equality. /// - Returns: `true` if the two merging publishers have equal source publishers, `false` otherwise. public static func == (lhs: Publishers.Merge8<A, B, C, D, E, F, G, H>, rhs: Publishers.Merge8<A, B, C, D, E, F, G, H>) -> Bool } extension Publishers.MergeMany : Equatable where Upstream : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Publishers.MergeMany<Upstream>, rhs: Publishers.MergeMany<Upstream>) -> Bool } extension Publishers.Retry : Equatable where Upstream : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Publishers.Retry<Upstream>, rhs: Publishers.Retry<Upstream>) -> Bool } extension Publishers.Zip : Equatable where A : Equatable, B : Equatable { /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A zip publisher to compare for equality. /// - rhs: Another zip publisher to compare for equality. /// - Returns: `true` if the corresponding upstream publishers of each zip publisher are equal, `false` otherwise. public static func == (lhs: Publishers.Zip<A, B>, rhs: Publishers.Zip<A, B>) -> Bool } /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A zip publisher to compare for equality. /// - rhs: Another zip publisher to compare for equality. /// - Returns: `true` if the corresponding upstream publishers of each zip publisher are equal, `false` otherwise. extension Publishers.Zip3 : Equatable where A : Equatable, B : Equatable, C : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Publishers.Zip3<A, B, C>, rhs: Publishers.Zip3<A, B, C>) -> Bool } /// Returns a Boolean value that indicates whether two publishers are equivalent. /// /// - Parameters: /// - lhs: A zip publisher to compare for equality. /// - rhs: Another zip publisher to compare for equality. /// - Returns: `true` if the corresponding upstream publishers of each zip publisher are equal, `false` otherwise. extension Publishers.Zip4 : Equatable where A : Equatable, B : Equatable, C : Equatable, D : Equatable { /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Publishers.Zip4<A, B, C, D>, rhs: Publishers.Zip4<A, B, C, D>) -> Bool }
57.366469
587
0.660985
673c0bba406b00fcd770e93c39e2e2846123451e
4,735
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import Chatto import ChattoAdditions class DemoChatViewController: BaseChatViewController { var messageSender: FakeMessageSender! var dataSource: FakeDataSource! { didSet { self.chatDataSource = self.dataSource } } lazy private var baseMessageHandler: BaseMessageHandler = { return BaseMessageHandler(messageSender: self.messageSender) }() override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "bubble-incoming-tail-border", in: Bundle(for: DemoChatViewController.self), compatibleWith: nil)?.bma_tintWithColor(.blue) super.chatItemsDecorator = ChatItemsDemoDecorator() let addIncomingMessageButton = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(DemoChatViewController.addRandomIncomingMessage)) self.navigationItem.rightBarButtonItem = addIncomingMessageButton } @objc private func addRandomIncomingMessage() { self.dataSource.addRandomIncomingMessage() } var chatInputPresenter: BasicChatInputBarPresenter! override func createChatInputView() -> UIView { let chatInputView = ChatInputBar.loadNib() var appearance = ChatInputBarAppearance() appearance.sendButtonAppearance.title = NSLocalizedString("Send", comment: "") appearance.textInputAppearance.placeholderText = NSLocalizedString("Type a message", comment: "") self.chatInputPresenter = BasicChatInputBarPresenter(chatInputBar: chatInputView, chatInputItems: self.createChatInputItems(), chatInputBarAppearance: appearance) chatInputView.maxCharactersCount = 1000 return chatInputView } override func createPresenterBuilders() -> [ChatItemType: [ChatItemPresenterBuilderProtocol]] { let textMessagePresenter = TextMessagePresenterBuilder( viewModelBuilder: DemoTextMessageViewModelBuilder(), interactionHandler: DemoTextMessageHandler(baseHandler: self.baseMessageHandler) ) textMessagePresenter.baseMessageStyle = BaseMessageCollectionViewCellAvatarStyle() let photoMessagePresenter = PhotoMessagePresenterBuilder( viewModelBuilder: DemoPhotoMessageViewModelBuilder(), interactionHandler: DemoPhotoMessageHandler(baseHandler: self.baseMessageHandler) ) photoMessagePresenter.baseCellStyle = BaseMessageCollectionViewCellAvatarStyle() return [ DemoTextMessageModel.chatItemType: [ textMessagePresenter ], DemoPhotoMessageModel.chatItemType: [ photoMessagePresenter ], SendingStatusModel.chatItemType: [SendingStatusPresenterBuilder()], TimeSeparatorModel.chatItemType: [TimeSeparatorPresenterBuilder()] ] } func createChatInputItems() -> [ChatInputItemProtocol] { var items = [ChatInputItemProtocol]() items.append(self.createTextInputItem()) items.append(self.createPhotoInputItem()) return items } private func createTextInputItem() -> TextChatInputItem { let item = TextChatInputItem() item.textInputHandler = { [weak self] text in self?.dataSource.addTextMessage(text) } return item } private func createPhotoInputItem() -> PhotosChatInputItem { let item = PhotosChatInputItem(presentingController: self) item.photoInputHandler = { [weak self] image in self?.dataSource.addPhotoMessage(image) } return item } }
41.173913
170
0.723759
1a60e005df047a7ca72f4765b384949ed2d9872a
4,264
// // 🦠 Corona-Warn-App // import Foundation import AnyCodable import CertLogic struct SystemTime: Codable { // MARK: - Init init(_ date: Date) { self.timestamp = Int(date.timeIntervalSince1970) self.localDate = SystemTime.localDateFormatter.string(from: date) self.localDateTime = SystemTime.localDateTimeFormatter.string(from: date) self.localDateTimeMidnight = SystemTime.localDateMidnightTimeFormatter.string(from: date) self.utcDate = SystemTime.utcDateFormatter.string(from: date) self.utcDateTime = SystemTime.utcDateTimeFormatter.string(from: date) self.utcDateTimeMidnight = SystemTime.utcDateTimeMidnightFormatter.string(from: date) } // MARK: - Internal let timestamp: Int let localDate: String let localDateTime: String let localDateTimeMidnight: String let utcDate: String let utcDateTime: String let utcDateTimeMidnight: String } enum CCLDefaultInput { static func addingTo( parameters: [String: AnyDecodable], date: Date = Date(), language: String = Locale.current.languageCode ?? "en" ) -> [String: AnyDecodable] { var parametersWithDefaults = parameters parametersWithDefaults["os"] = AnyDecodable("ios") parametersWithDefaults["language"] = AnyDecodable(language) parametersWithDefaults["now"] = AnyDecodable(SystemTime(date)) return parametersWithDefaults } } enum GetWalletInfoInput { static func make( with date: Date = Date(), language: String = Locale.current.languageCode ?? "en", certificates: [DCCWalletCertificate], boosterNotificationRules: [Rule], identifier: String? ) -> [String: AnyDecodable] { return CCLDefaultInput.addingTo( parameters: [ "certificates": AnyDecodable(certificates), "boosterNotificationRules": AnyDecodable(boosterNotificationRules), "scenarioIdentifier": AnyDecodable(identifier) ], date: date, language: language ) } } enum GetAdmissionCheckScenariosInput { static func make( with date: Date = Date(), language: String = Locale.current.languageCode ?? "en" ) -> [String: AnyDecodable] { return CCLDefaultInput.addingTo( parameters: [:], date: date, language: language ) } } extension SystemTime { // MARK: - DateFormatters static let localDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeZone = TimeZone.autoupdatingCurrent formatter.dateFormat = "yyyy-MM-dd" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.calendar = Calendar(identifier: .gregorian) return formatter }() // 2021-12-30T10:00:00+01:00 static let localDateTimeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeZone = TimeZone.autoupdatingCurrent formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssxxx" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.calendar = Calendar(identifier: .gregorian) return formatter }() // 2021-12-30T00:00:00+01:00 static let localDateMidnightTimeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeZone = TimeZone.autoupdatingCurrent formatter.dateFormat = "yyyy-MM-dd'T00:00:00'xxx" formatter.locale = Locale(identifier: "en_US_POSIX") formatter.calendar = Calendar(identifier: .gregorian) return formatter }() static let utcDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.locale = Locale(identifier: "en_US_POSIX") formatter.calendar = Calendar(identifier: .gregorian) return formatter }() // 2021-12-30T09:00:00Z static let utcDateTimeFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.locale = Locale(identifier: "en_US_POSIX") formatter.calendar = Calendar(identifier: .gregorian) return formatter }() // 2021-12-30T00:00:00Z static let utcDateTimeMidnightFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T00:00:00Z'" formatter.timeZone = TimeZone(abbreviation: "UTC") formatter.locale = Locale(identifier: "en_US_POSIX") formatter.calendar = Calendar(identifier: .gregorian) return formatter }() }
29.006803
91
0.745544
d93aba7f7ba888966d185e2182d6dcd38c07c046
9,304
// // PhotoEditor+Gestures.swift // Photo Editor // // Created by Mohamed Hamed on 6/16/17. // // import Foundation import UIKit extension PhotoEditorViewController : UIGestureRecognizerDelegate { /** UIPanGestureRecognizer - Moving Objects Selecting transparent parts of the imageview won't move the object */ @objc func panGesture(_ recognizer: UIPanGestureRecognizer) { if let view = recognizer.view { if view is UIImageView { //Tap only on visible parts on the image if recognizer.state == .began { for imageView in subImageViews(view: canvasImageView) { let location = recognizer.location(in: imageView) let alpha = imageView.alphaAtPoint(location) if alpha > 0 { imageViewToPan = imageView break } } } if imageViewToPan != nil { moveView(view: imageViewToPan!, recognizer: recognizer) } } else { moveView(view: view, recognizer: recognizer) } if view is UITextView { let textVIew = view as! UITextView if recognizer.state == .began || recognizer.state == .changed { textVIew.isEditable = false } else { textVIew.isEditable = true } } } } /** UIPinchGestureRecognizer - Pinching Objects If it's a UITextView will make the font bigger so it doen't look pixlated */ @objc func pinchGesture(_ recognizer: UIPinchGestureRecognizer) { if let view = recognizer.view { if view is UITextView { let textView = view as! UITextView textView.isEditable = false if textView.font!.pointSize * recognizer.scale < 90 { let font = UIFont(name: textView.font!.fontName, size: textView.font!.pointSize * recognizer.scale) textView.font = font let sizeToFit = textView.sizeThatFits(CGSize(width: UIScreen.main.bounds.size.width, height:CGFloat.greatestFiniteMagnitude)) textView.bounds.size = CGSize(width: textView.intrinsicContentSize.width, height: sizeToFit.height) } else { let sizeToFit = textView.sizeThatFits(CGSize(width: UIScreen.main.bounds.size.width, height:CGFloat.greatestFiniteMagnitude)) textView.bounds.size = CGSize(width: textView.intrinsicContentSize.width, height: sizeToFit.height) } if recognizer.state == .ended { textView.isEditable = true } textView.setNeedsDisplay() } else { view.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale) } recognizer.scale = 1 } } /** UIRotationGestureRecognizer - Rotating Objects */ @objc func rotationGesture(_ recognizer: UIRotationGestureRecognizer) { if let view = recognizer.view { view.transform = view.transform.rotated(by: recognizer.rotation) recognizer.rotation = 0 } } /** UITapGestureRecognizer - Taping on Objects Will make scale scale Effect Selecting transparent parts of the imageview won't move the object */ @objc func tapGesture(_ recognizer: UITapGestureRecognizer) { if let view = recognizer.view { if view is UIImageView { //Tap only on visible parts on the image for imageView in subImageViews(view: canvasImageView) { let location = recognizer.location(in: imageView) let alpha = imageView.alphaAtPoint(location) if alpha > 0 { scaleEffect(view: imageView) break } } } else { scaleEffect(view: view) } } } /* Support Multiple Gesture at the same time */ public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } @objc func screenEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) { if recognizer.state == .recognized { if !stickersVCIsVisible { addStickersViewController() } } } // to Override Control Center screen edge pan from bottom override public var prefersStatusBarHidden: Bool { return true } /** Scale Effect */ func scaleEffect(view: UIView) { view.superview?.bringSubviewToFront(view) if #available(iOS 10.0, *) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() } let previouTransform = view.transform UIView.animate(withDuration: 0.2, animations: { view.transform = view.transform.scaledBy(x: 1.2, y: 1.2) }, completion: { _ in UIView.animate(withDuration: 0.2) { view.transform = previouTransform } }) } /** Moving Objects delete the view if it's inside the delete view Snap the view back if it's out of the canvas */ func moveView(view: UIView, recognizer: UIPanGestureRecognizer) { hideToolbar(hide: true) deleteView.isHidden = false view.superview?.bringSubviewToFront(view) let pointToSuperView = recognizer.location(in: self.view) view.center = CGPoint(x: view.center.x + recognizer.translation(in: canvasImageView).x, y: view.center.y + recognizer.translation(in: canvasImageView).y) recognizer.setTranslation(CGPoint.zero, in: canvasImageView) if let previousPoint = lastPanPoint { //View is going into deleteView if deleteView.frame.contains(pointToSuperView) && !deleteView.frame.contains(previousPoint) { if #available(iOS 10.0, *) { let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() } UIView.animate(withDuration: 0.3, animations: { view.transform = view.transform.scaledBy(x: 0.25, y: 0.25) view.center = recognizer.location(in: self.canvasImageView) }) } //View is going out of deleteView else if deleteView.frame.contains(previousPoint) && !deleteView.frame.contains(pointToSuperView) { //Scale to original Size UIView.animate(withDuration: 0.3, animations: { view.transform = view.transform.scaledBy(x: 4, y: 4) view.center = recognizer.location(in: self.canvasImageView) }) } } lastPanPoint = pointToSuperView if recognizer.state == .ended { imageViewToPan = nil lastPanPoint = nil hideToolbar(hide: false) deleteView.isHidden = true let point = recognizer.location(in: self.view) if deleteView.frame.contains(point) { // Delete the view view.removeFromSuperview() if #available(iOS 10.0, *) { let generator = UINotificationFeedbackGenerator() generator.notificationOccurred(.success) } } else if !canvasImageView.bounds.contains(view.center) { //Snap the view back to canvasImageView UIView.animate(withDuration: 0.3, animations: { view.center = self.canvasImageView.center }) } } } func subImageViews(view: UIView) -> [UIImageView] { var imageviews: [UIImageView] = [] for imageView in view.subviews { if imageView is UIImageView { imageviews.append(imageView as! UIImageView) } } return imageviews } }
37.821138
164
0.541702
50ca6c11a299db8bfb6ad7bfe08defc85028e6e5
6,028
// // ViewController.swift // Prework // // Created by mihir suvarna on 6/3/21. // import UIKit class ViewController: UIViewController { // Required Variables @IBOutlet weak var billAmountTextField: UITextField! @IBOutlet weak var tipAmountLabel: UILabel! @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var totalLabel: UILabel! // Self-created Variables for Theme @IBOutlet weak var billAmountLeftLabel: UILabel! @IBOutlet weak var tipLeftLabel: UILabel! @IBOutlet weak var totalLeftLabel: UILabel! @IBOutlet weak var tipAmountSlider: UISlider! @IBOutlet weak var tipAmountPercentLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Sets title for this app self.title = "What's The Tip?" // Add an observer and setup the darkMode function let darkMode = Notification.Name("darkMode enabled") NotificationCenter.default.addObserver(self, selector: #selector(enableDarkMode), name: darkMode, object: nil) enableDarkMode() // Add an observer and setup the tipSlider function let slider = Notification.Name("tipSlider enabled") NotificationCenter.default.addObserver(self, selector: #selector(tipSliderOn), name: slider, object: nil) tipSliderOn() } @objc func tipSliderOn() { // Basic function to check if tipSlider is on/off let isTipSliderHidden = UserDefaults.standard.bool(forKey: "tipSliderOn") tipAmountSlider.isHidden = !isTipSliderHidden tipAmountPercentLabel.isHidden = !isTipSliderHidden print("hidden") } @objc func enableDarkMode() { // Basic function to check if darkMode is on/off let isDarkMode = UserDefaults.standard.bool(forKey: "isDarkMode") let theme = isDarkMode ? ThemeType.black : ThemeType.white // Update the navbar colors navigationController?.navigationBar.barTintColor = theme.backgroundColor navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : theme.textColor] navigationController?.navigationBar.barStyle = isDarkMode ? .black : .default // Assign theme to UI elements view.backgroundColor = theme.backgroundColor // Set labels to correct theme billAmountLeftLabel.textColor = theme.textColor tipLeftLabel.textColor = theme.textColor totalLeftLabel.textColor = theme.textColor tipAmountPercentLabel.textColor = theme.textColor totalLabel.textColor = theme.textColor tipAmountLabel.textColor = theme.textColor // Update the text field and keyboard billAmountTextField.textColor = theme.accentColor billAmountTextField.tintColor = theme.accentColor billAmountTextField.backgroundColor = theme.secondAccentColor billAmountTextField.keyboardAppearance = isDarkMode ? UIKeyboardAppearance.dark : UIKeyboardAppearance.light tipControl.backgroundColor = theme.secondAccentColor // Update the segmented control let titleTextAttributes = [NSAttributedString.Key.foregroundColor: theme.accentColor] UISegmentedControl.appearance().setTitleTextAttributes(titleTextAttributes, for: .normal) } @IBAction func calculateTip(_ sender: Any) { // Grab the bill amount let bill = Double(billAmountTextField.text!) ?? 0 // Calculate tip and total using an array let tipPercentages = [0.15, 0.18, 0.2] let tipIndex = tipPercentages[tipControl.selectedSegmentIndex] let tip = bill * tipIndex let total = bill + tip; // Format the total let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency // Update tip and total amount labels // tipAmountLabel.text = String(format: "$%.2f", total) // totalLabel.text = String(format: "$%.2f", total) tipAmountLabel.text = numberFormatter.string(for: tip) totalLabel.text = numberFormatter.string(for: total) // Update the tipSlider with selected segment value if (UserDefaults.standard.object(forKey: "tipSliderOn") != nil) { if UserDefaults.standard.bool(forKey: "tipSliderOn") { tipAmountSlider.setValue(Float(tipIndex), animated: true) tipAmountPercentLabel.text = String(format: "%.2f%%", 100 * tipAmountSlider.value) } } } @IBAction func calculateTipSlider(_ sender: Any) { tipAmountPercentLabel.text = String(format: "%.2f%%", 100 * tipAmountSlider.value) let bill = Float(billAmountTextField.text!) ?? 0 // Calculate tip and total using an array let tip = bill * tipAmountSlider.value let total = bill + tip; // Format the total let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .currency // Update tip and total amount labels // tipAmountLabel.text = String(format: "$%.2f", total) // totalLabel.text = String(format: "$%.2f", total) tipAmountLabel.text = numberFormatter.string(for: tip) totalLabel.text = numberFormatter.string(for: total) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("view will appear") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) billAmountTextField.becomeFirstResponder() print("view did appear") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("view will disappear") } override func viewDidDisappear(_ animated: Bool) { super.viewDidAppear(animated) print("view did disappear") } }
38.394904
124
0.660418
fe51b2e0864971ac05b6705198b00f775f4720e9
364
// // TestProductRequester.swift // FairyTales // // Created by Pavel Gnatyuk on 27/05/2017. // // import Foundation import StoreKit class TestProductRequester: ProductRequester { var counter = 0 func request(identifiers: Set<String>, onComplete: @escaping (([SKProduct], [String]) -> Void)) -> Bool { counter += 1 return true } }
19.157895
109
0.653846
4a35aa2fbf67b0a2bcdfc47e9f672891c049b267
462
import SwiftUI struct LineShape: Shape { var data: ChartData func path(in rect: CGRect) -> Path { let path = Path.quadCurvedPathWithPoints(data: data, step: CGPoint(x: 1.0, y: 1.0)) return path } } struct LineShapeComparison: Shape { var data: ChartData func path(in rect: CGRect) -> Path { let path = Path.quadCurvedPathWithPointsComparison(data: data, step: CGPoint(x: 1.0, y: 1.0)) return path } }
22
101
0.634199
221a362fc7bb994890e7d1c6e69c3bb0075bafef
7,291
// // AgsUser.swift // AGSAuth import Foundation /** Represents the user roles. It has 2 types - Realm - Client A user role is a realm role if the nameSpace is not set. Otherwise it is a client role. */ struct UserRole: Hashable { /** Supported role types for UserRole. */ enum Types { case REALM, CLIENT } /** namespace of the role. It should be empty or nil for realm roles. Otherwise it should be the client name for a client role */ let nameSpace: String? /** the name of the role */ let roleName: String /** the type of the role */ var roleType: Types { if let nspace = nameSpace { if nspace.isEmpty { return Types.REALM } else { return Types.CLIENT } } else { return Types.REALM } } var hashValue: Int { if let nspace = nameSpace { return nspace.hashValue ^ roleName.hashValue } else { return roleName.hashValue } } static func == (lhs: UserRole, rhs: UserRole) -> Bool { return lhs.nameSpace == rhs.nameSpace && lhs.roleName == rhs.roleName } } /** Describes the structure of user profile returned by Keycloak */ struct KeycloakUserProfile: Codable { /** Internal structure for AccessRoles. The JSON object contains other fields but we are only interested in "roles" */ struct AccessRoles: Codable { let roles: [String]? } private let name: String? private let preferredName: String? private let realmAccess: AccessRoles? private let resourceAccess: [String: AccessRoles]? /** first name of Keycloak user */ let firstName: String? /** last name of Keycloak user */ let lastName: String? /** email of Keycloak user */ let email: String? /** The properties used for the `KeycloakUserProfile` representation */ enum CodingKeys: String, CodingKey { case name case preferredName = "preferred_username" case email case realmAccess = "realm_access" case resourceAccess = "resource_access" case firstName = "given_name" case lastName = "family_name" } /** Get the name of the user. If `preferred_username` is set, it will be used. Otherwise `name` field will be used */ var username: String? { return preferredName ?? (name ?? nil) } /** Return all the realm roles of the user */ var realmRoles: [String] { guard let realmData = realmAccess, let realmRoles = realmData.roles else { return [String]() } return realmRoles } /** Return the client roles of the user. - parameters: - clientName: the name of the client - returns: an array of the role names */ func getClientRoles(_ clientName: String) -> [String] { guard let resourceData = resourceAccess, let clientData = resourceData[clientName], let clientRoles = clientData.roles else { return [String]() } return clientRoles } /** Return both realm roles and client roles of the user. - parameters: - clientName: the name of the client - returns: a set of UserRole */ func getUserRoles(forClient clientName: String) -> Set<UserRole> { var userRoles = Set<UserRole>() for role in realmRoles { if !role.isEmpty { userRoles.insert(UserRole(nameSpace: nil, roleName: role)) } } let clientRoles = getClientRoles(clientName) for role in clientRoles { if !role.isEmpty { userRoles.insert(UserRole(nameSpace: clientName, roleName: role)) } } return userRoles } } /** Represents a user. */ public struct User { /** Username */ public let userName: String? /** Email */ public let email: String? /** First Name */ public let firstName: String? /** Last Name */ public let lastName: String? /** Realm roles and client roles of the user */ var roles: Set<UserRole> = Set<UserRole>() /** Realm roles of the user */ public var realmRoles: [String] { let realmRoles = roles.filter({ $0.roleType == UserRole.Types.REALM }).map({ $0.roleName }) return realmRoles } /** Client roles of the user */ public var clientRoles: [String] { let clientRoles = roles.filter({ $0.roleType == UserRole.Types.CLIENT }).map({ $0.roleName }) return clientRoles } /** Raw value of the access token. Should be used to perform other requests */ public let accessToken: String? /** Identity token */ public let identityToken: String? /** Full Name built using firstName and lastName. If both are not set or empty, nil will be returned */ public var fullName: String? { let name = "\(firstName ?? "") \(lastName ?? "")" if name.isEmpty { return nil } return name } /** Used for testing */ init(userName: String?, email: String?, firstName: String?, lastName: String?, accessToken: String?, identityToken: String?, roles: Set<UserRole>?) { self.userName = userName self.email = email self.firstName = firstName self.lastName = lastName self.accessToken = accessToken self.identityToken = identityToken if let _ = roles { self.roles = roles! } } /** Build the User instance from the credential data and the Keycloak client name. - parameters: - credential: the `OIDCCredentials` - clientName: the name of the Keycloak client */ init?(credential: OIDCCredentials, clientName: String) { guard let token = credential.accessToken, let jwt = try? Jwt.decode(token) else { return nil } let payload = jwt.payload guard let keycloakUserProfile = try? JSONDecoder().decode(KeycloakUserProfile.self, from: payload) else { return nil } accessToken = token identityToken = credential.identityToken userName = keycloakUserProfile.username firstName = keycloakUserProfile.firstName lastName = keycloakUserProfile.lastName email = keycloakUserProfile.email roles = keycloakUserProfile.getUserRoles(forClient: clientName) } /** Check if the user has a client role. - parameters: - client: name of the client - role: name of the role to check - returns: true if user has the client role, otherwise false */ public func hasClientRole(client: String, role: String) -> Bool { let roleToFind = UserRole(nameSpace: client, roleName: role) return roles.contains(roleToFind) } /** Check if the user has a realm role. - parameters: - roleName: Name of the role - returns: true if user has the realm role, otherwise false */ public func hasRealmRole(_ roleName: String) -> Bool { let roleToFind = UserRole(nameSpace: nil, roleName: roleName) return roles.contains(roleToFind) } }
30.253112
153
0.605815
79987a72c63952bdecfe0b48a6c3d449b3274998
858
import UIKit class Solution { func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int { let gCount = gas.count let cCount = cost.count if gCount != cCount || gCount == 0 { return -1 } var start = 0 var end = 0 var tmp = 0 while start < cCount { tmp += gas[end] - cost[end] print(start, end) if tmp < 0 { if start > end { return -1 } start = end + 1 end = end + 1 tmp = 0 } else { end = (end + 1) % cCount if end == start { return start } } } return -1 } } Solution().canCompleteCircuit([1,2,3,4,5], [3,4,5,1,2])
23.833333
65
0.371795
d5704fcb83672f1b54c8be7bdf9e8db165a01f6c
539
// This source file is part of the https://github.com/ColdGrub1384/Pisth open source project // // Copyright (c) 2017 - 2018 Adrian Labbé // Licensed under Apache License v2.0 // // See https://raw.githubusercontent.com/ColdGrub1384/Pisth/master/LICENSE for license information import Foundation /// Reason for opening Pisth APT. enum OpenReason { /// Opened by the user. case `default` /// Opened by Pisth API to install a DEB package. case installDeb /// Open by Pisth API. case openConnection }
24.5
98
0.695733
f9ad5033cd2149710cb4124b87811088fafb84dc
2,891
// Copyright © 2020, Fueled Digital Media, LLC // // 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 extension UIScrollView { /// /// **Unavailable**: Please use `currentPage` instead. /// /// Refer to the documentation for `currentPage` for more info. /// @available(*, unavailable, renamed: "currentPage") public var lsd_currentPage: Int { return self.currentPage } /// /// **Unavailable**: Please use `numberOfPages` instead. /// /// Refer to the documentation for `numberOfPages` for more info. /// @available(*, unavailable, renamed: "numberOfPages") public var lsd_numberOfPages: Int { return self.numberOfPages } /// /// **Unavailable**: Please use `setCurrentPage(_:, animated:)` instead. /// /// Refer to the documentation for `setCurrentPage(_:, animated:)` for more info. /// @available(*, unavailable, renamed: "setCurrentPage(_:animated:)") public func lsd_setCurrentPage(_ page: Int, animated: Bool) { self.setCurrentPage(page, animated: animated) } /// /// Gets/Sets (without animation) the current page of the scroll view, assuming a paginated scroll view of width `self.bounds.size.width`, with no left or right content insets. /// /// To set the current page with an animation, use `setCurrentPage(_ page:, animated:)` /// /// - Returns: Returns the current page (0-based) /// public var currentPage: Int { get { let page = Int((self.contentOffset.x / self.bounds.size.width).rounded()) return min(max(0, page), self.numberOfPages - 1) } set { self.setCurrentPage(newValue, animated: false) } } /// /// Gets the total number of pages of the scroll view, assuming a paginated scroll view of width `self.bounds.size.width`, with no left or right content insets. /// /// - Returns: Returns the number of pages. /// public var numberOfPages: Int { return Int((self.contentSize.width / self.bounds.size.width).rounded(.up)) } /// /// Sets the current page of the scroll view, assuming a paginated scroll view of width `self.bounds.size.width`, with no left or right content insets. /// /// - Parameters: /// - page: The page to set to. /// - animated: Whether to animate the change or not. /// public func setCurrentPage(_ page: Int, animated: Bool) { let offset = CGPoint(x: self.bounds.size.width * CGFloat(page), y: 0) self.setContentOffset(offset, animated: animated) } }
33.616279
177
0.701487
876ced5afed952426bae0c06450d4b864669f6ca
218
// // Item.swift // iDine // // Created by pamarori mac on 14/09/20. // import Foundation struct Item: Identifiable { var id = UUID() var name: String var price: Int var quantity: Int }
11.473684
40
0.582569
fc1b06a1a0361e43c923ad9db1972b8ed3bfabf4
1,055
// // SetupConfigurator.swift // RememberPoint // // Created by Pavel Chehov on 03/01/2019. // Copyright © 2019 Pavel Chehov. All rights reserved. // import Foundation import UIKit protocol SetupConfiguratorProtocol: AnyObject { func configure(with viewController: SetupViewController) } class SetupConfigurator: SetupConfiguratorProtocol { func configure(with viewController: SetupViewController) { let router: SetupRouterProtocol = SetupRouter(for: viewController) let presenter: SetupPresenterProtocol = SetupPresenter(for: viewController, with: router) let interactor: SetupInteractorProtocol = SetupInteractor( locationManager: DIContainer.instance.resolve(), reminderService: DIContainer.instance.resolve(), notificationService: DIContainer.instance.resolve(), settingsProvider: DIContainer.instance.resolve() ) presenter.configure(with: interactor) viewController.presenter = presenter viewController.hideNavigationBar() } }
34.032258
97
0.727962
d7bcdc994afcfa74431659c82ccb3d63ba4e2eff
1,148
// // PostDetailsRouter.swift // TheBlog // // Created by Marcio Garcia on 07/06/20. // Copyright (c) 2020 Oxl Tech. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so // you can apply clean architecture to your iOS and Mac projects, // see http://clean-swift.com // import UIKit protocol PostDetailsRoutingLogic { var dataStore: PostDetailsDataStore? { get } func routeToFullScreenImage(imageUrl: String?, image: UIImage?, imageWorker: ImageWorkLogic?) } protocol PostDetailsDataPassing { var dataStore: PostDetailsDataStore? { get } } class PostDetailsRouter: PostDetailsRoutingLogic, PostDetailsDataPassing { weak var viewController: PostDetailsViewController? var dataStore: PostDetailsDataStore? init(dataStore: PostDetailsDataStore?) { self.dataStore = dataStore } func routeToFullScreenImage(imageUrl: String?, image: UIImage?, imageWorker: ImageWorkLogic?) { let vc = FullImageViewController(imageUrl: nil, image: image, imageWorker: imageWorker) viewController?.navigationController?.pushViewController(vc, animated: true) } }
30.210526
99
0.741289
33675129c001b502bb899be65d2ae43e519969b9
226
// RUN: %target-typecheck-verify-swift protocol P: class {} protocol P1: AnyObject {} protocol P2 {} protocol P3: class, P2 {} protocol P4: P2, class {} // expected-error {{'class' must come first in the requirement list}}
28.25
95
0.69469
d6c6d82f591f27097074ebf4e85b81dfe20f0a7d
1,215
// // SelfTestingCoronaSuspicionViewModel.swift // CoronaContact // import Foundation import Resolver class SelfTestingCoronaSuspicionViewModel: ViewModel { @Injected private var localStorage: LocalStorage weak var coordinator: SelfTestingCoronaSuspicionCoordinator? init(with coordinator: SelfTestingCoronaSuspicionCoordinator) { self.coordinator = coordinator } func showRevocation() { guard let coordinator = coordinator else { return } let child = SicknessCertificateCoordinator(navigationController: coordinator.navigationController) coordinator.addChildCoordinator(child) child.start() } func showStatusReport() { guard let coordinator = coordinator else { return } let child = SelfTestingPersonalDataCoordinator(navigationController: coordinator.navigationController) coordinator.addChildCoordinator(child) child.start() } func saveSelectedReportDate(reportDate: Date) { localStorage.hasSymptomsOrPositiveAttestAt = reportDate } func viewClosed() { localStorage.hasSymptomsOrPositiveAttestAt = nil } }
27.613636
110
0.699588
5b737d4e3255b1ba4983000eebfe8731fcf343d4
642
// // Conference.swift // // // Created by Arminas on 2019-09-28. // import Foundation import Combine public struct Conference: Codable { public let name: String public let start: Date? public let end: Date? public let location: String? public let link: URL? public let cfp: CFP? } public struct CFP: Codable { public let link: URL? public let deadline: Date? public var containsLinkAndDeadline: Bool { containsLink && containsDeadline } public var containsLink: Bool { link != nil } public var containsDeadline: Bool { deadline != nil } }
17.833333
46
0.624611
c1d8d7c752dd075f59333f19bc8e9b2b5683412b
383
// RUN: rm -rf %t && mkdir %t // RUN: touch %t/main.swiftmodule %t/main.swiftdoc // RUN: chmod -w %t // RUN: %target-swift-frontend -emit-module -emit-module-doc -parse-stdlib -o %t -module-name main %s || chmod +w %t // This is not combined with the previous chmod because of pipefail mode. // RUN: chmod +w %t // RUN: test -s %t/main.swiftmodule // RUN: test -s %t/main.swiftdoc
34.818182
116
0.663185
8f514981377732dde46f9c977c2711b4a8c1cbb3
2,171
// // AppDelegate.swift // MultiSpeedSlider // // Created by Cyon Alexander (Ext. Netlight) on 08/12/15. // Copyright © 2015 com.cyonalex. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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:. } }
46.191489
285
0.754491
905461631efd70a46955ed25d992d16df88a5d39
1,102
// // Pricingprotocols.swift // // Created by Kevin Taniguchi on 7/7/16. // import Foundation import UIKit typealias PriceRange = (lowPriceString: NSAttributedString?, highPriceString: NSAttributedString?) private let currencyNumberFormatter = NSNumberFormatter() public protocol AttributedPrices { var strikeThroughColor: UIColor { get } var salePriceColor: UIColor { get } } public protocol AttributedPricesForSummarySheet: AttributedPrices { func attributedPrice(price: NSNumber) -> NSAttributedString? } public protocol AttributedPricesWithPromos: AttributedPrices { func attributedPriceString(withPromo promo: NSAttributedString?) -> NSAttributedString? } public protocol AttributedSale: AttributedPrices { var isSale: Bool { get } var isMarkDown: Bool { get } } public protocol AttributedProductPromotion { var promoString: NSAttributedString? { get } } public protocol AttributedRangePrice: AttributedPrices { var rangedListString: NSAttributedString? { get } var rangedSaleString: NSAttributedString? { get } var hasPriceRange: Bool { get } }
26.878049
98
0.770417
fcfaae73c60d0fb9e85b11ccd72b819291d6acfe
2,186
// // AppDelegate.swift // SFCloudMusicFunctionKit // // Created by shcamaker on 02/21/2020. // Copyright (c) 2020 shcamaker. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. } }
46.510638
285
0.755718
e51dc6126f912702692711cdaf145c2bdccba6d6
3,308
// // Common.swift // xxHash-Swift // // Created by Daisuke T on 2019/02/14. // Copyright © 2019 xxHash-Swift. All rights reserved. // import Foundation import xxHash_Swift class Common { // MARK: - One-shot static func oneshotXXH32() { do { let hash = XXH32.digest("123456789ABCDEF") print("XXH32 One-shot -> 0x\(String(format: "%08x", hash))") } do { let hash = XXH32.digest("123456789ABCDEF", seed: 0x7fffffff) print("XXH32 One-shot(0x7fffffff) -> 0x\(String(format: "%08x", hash))") } } static func oneshotXXH64() { do { let hash = XXH64.digest("123456789ABCDEF") print("XXH64 One-shot -> 0x\(String(format: "%016lx", hash))") } do { let hash = XXH64.digest("123456789ABCDEF", seed: 0x000000007fffffff) print("XXH64 One-shot(0x000000007fffffff) -> 0x\(String(format: "%016lx", hash))") } } static func oneshotXXH3_64() { do { let hash = XXH3.digest64("123456789ABCDEF") print("XXH3-64 One-shot -> 0x\(String(format: "%016lx", hash))") } do { let hash = XXH3.digest64("123456789ABCDEF", seed: 0x000000007fffffff) print("XXH3-64 One-shot(0x000000007fffffff) -> 0x\(String(format: "%016lx", hash))") } } static func oneshotXXH3_128() { do { let hash = XXH3.digest128("123456789ABCDEF") print("XXH3-128 One-shot -> 0x\(String(format: "%016lx%016lx", hash[0], hash[1]))") } do { let hash = XXH3.digest128("123456789ABCDEF", seed: 0x000000007fffffff) print("XXH3-128 One-shot(0x000000007fffffff) -> 0x\(String(format: "%016lx%016lx", hash[0], hash[1]))") } } // MARK: - Streaming static func streamingXXH32() { // Create xxHash instance let xxh = XXH32() // if using seed, e.g. "XXH32(0x7fffffff)" // Get data from file let bundle = Bundle(for: Common.self) let path = bundle.path(forResource: "alice29", ofType: "txt")! let data = NSData(contentsOfFile: path)! as Data let bufSize = 1024 var index = 0 repeat { var lastIndex = index + bufSize if lastIndex > data.count { lastIndex = index + data.count - index } let data2 = data[index..<lastIndex] xxh.update(data2) index += data2.count if index >= data.count { break } } while(true) let hash = xxh.digest() print("XXH32 Streaming -> 0x\(String(format: "%08x", hash))") } static func streamingXXH64() { // Create xxHash instance let xxh = XXH64() // if using seed, e.g. "XXH64(0x000000007fffffff)" // Get data from file let bundle = Bundle(for: Common.self) let path = bundle.path(forResource: "alice29", ofType: "txt")! let data = NSData(contentsOfFile: path)! as Data let bufSize = 1024 var index = 0 repeat { var lastIndex = index + bufSize if lastIndex > data.count { lastIndex = index + data.count - index } let data2 = data[index..<lastIndex] xxh.update(data2) index += data2.count if index >= data.count { break } } while(true) let hash = xxh.digest() print("XXH64 Streaming -> 0x\(String(format: "%016lx", hash))") } }
25.446154
109
0.584643
f761c7519431a25419deae064f0148fa023809eb
684
import DistWorkerModels import DistWorkerModelsTestHelpers import Foundation import XCTest final class FixedWorkerConfigurationsTests: XCTestCase { lazy var configurations = FixedWorkerConfigurations() func test__if_worker_is_unknown__configuration_is_nil() { XCTAssertNil(configurations.workerConfiguration(workerId: "worker")) } func test__if_worker_unknown__configuration_is_expected() { let config = WorkerConfigurationFixtures.workerConfiguration configurations.add(workerId: "some_worker", configuration: config) XCTAssertEqual(configurations.workerConfiguration(workerId: "some_worker"), config) } }
32.571429
91
0.769006
1cff4d2460e68c403153954fb85ba9dd286347ac
1,154
import Cocoa @propertyWrapper struct ControlStringValue { var control: NSControl! var wrappedValue: String { get { control.stringValue } set { control.stringValue = newValue } } var projectedValue: NSControl? { get { control } set { control = newValue } } } @propertyWrapper struct ControlURLValue { var control: NSControl! var wrappedValue: URL? { get { URL(string: control.stringValue) } set { control.stringValue = newValue?.absoluteString ?? "" } } var projectedValue: NSControl? { get { control } set { control = newValue } } } @propertyWrapper struct ControlBoolValue { var control: NSControl! var wrappedValue: Bool { get { control.boolValue } set { control.boolValue = newValue } } var projectedValue: NSControl? { get { control } set { control = newValue } } } @propertyWrapper struct TextViewString { var textView: NSTextView! var wrappedValue: String { get { textView.string } set { textView.string = newValue } } var projectedValue: NSTextView? { get { textView } set { textView = newValue } } }
16.485714
64
0.645581
3939e6d21f95f3e66476eaabb86cdf4a4793eeee
4,268
// // SVMPCALetterRecognizer.swift // Snowman // // Created by Conrad Stoll on 7/30/17. // Copyright © 2017 Conrad Stoll. 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 Accelerate import CoreML import Foundation protocol SVMModel { func predictionResult(from inputArray: MLMultiArray) throws -> SVMModelOutput } protocol SVMModelOutput { var letterIndex : Int64 { get } var classProbability: [Int64 : Double] { get } } class SVMPCALetterRecognizer : LetterRecognizing { let model : SVMModel init(_ model : SVMModel) { self.model = model } func recognizeLetter(for drawing: LetterDrawing) -> [LetterPrediction] { let pixelAlpha = drawing.generateImageVectorForAlphaChannel() let inputVector = PCAMatrix.shared.transform(from: pixelAlpha) do { let multiArray = try MLMultiArray(shape: [25], dataType: MLMultiArrayDataType.float32) for (index, number) in inputVector.enumerated() { multiArray[index] = number } let prediction = try model.predictionResult(from: multiArray) let predictions = letterPredictions(from: prediction) return predictions } catch { print(error) } return [LetterPrediction]() } fileprivate func letterPredictions(from output : SVMModelOutput) -> [LetterPrediction] { var predictions = [LetterPrediction]() for i in 1...letterMapping.count { let index = Int64(i) let confidence = output.classProbability[index] ?? 0.0 let letter = String(i).letter() let prediction = LetterPrediction(letter: letter, confidence: confidence) predictions.append(prediction) } let sortedPredictions = predictions.sorted { (p1, p2) -> Bool in return p1.confidence > p2.confidence } let filteredPredictions = sortedPredictions.filter { (p) -> Bool in return p.confidence > 0.05 } return filteredPredictions } } fileprivate class PCAMatrix { static let shared = PCAMatrix() let pca : [Float] init() { pca = PCAMatrix.loadPCAFromCSV() } static func loadPCAFromCSV() -> [Float] { let path = Bundle.main.path(forResource: "pca", ofType: "csv")! let stream = InputStream(fileAtPath: path)! let csv = try! CSVReader(stream: stream) var matrix : [Float] = [Float]() var arrays : [[Float]] = [[Float]]() while let row = csv.next() { var array = [Float]() for item in row { let number = Float(item) ?? 0.0 array.append(number) } arrays.append(array) } var pcaString = "" for w in 0...Int(784) - 1 { for h in 0...Int(25) - 1 { let number = arrays[h][w] matrix.append(number) pcaString += String(number) + "," } } return matrix } // Input: 784 // Output: 25 fileprivate func transform(from input: [NSNumber]) -> [NSNumber] { let image = input.map { $0.floatValue } var result = [Float](repeating: 0.0, count: 25) vDSP_mmul(image, 1, pca, 1, &result, 1, 1, 25, 784) print(result) let transformed = result.map { NSNumber(value: $0) } return transformed } }
28.837838
98
0.565604
2181b683935b58ab47c6f077b5637859cd7f3eaf
423
// swift-tools-version:5.3 import PackageDescription let package = Package( name: "OutlineView", products: [ .library( name: "OutlineView", targets: ["OutlineView"]), ], targets: [ .target( name: "OutlineView", dependencies: []), .testTarget( name: "OutlineViewTests", dependencies: ["OutlineView"]), ] )
20.142857
43
0.510638
bb6db66583d67224fcbeef5d66d69cdf5c52ac6c
901
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -primary-file %s -parse-as-library -emit-ir -O | %FileCheck %s // Two thunks are generated: // 1. from function signature opts // 2. the witness thunk // Both should not inline the testit function and should set the noinline-attribute for llvm. // CHECK-LABEL: define hidden swiftcc i32 @{{.*}}testit{{.*}}F(i32) // CHECK: call swiftcc i32 @{{.*}}testit{{.*}}Tf{{.*}} #[[ATTR:[0-9]+]] // CHECK: ret // CHECK-LABEL: define hidden swiftcc i32 @{{.*}}testit{{.*}}FTW(i32 // CHECK: call swiftcc i32 @{{.*}}testit{{.*}}Tf{{.*}} #[[ATTR]] // CHECK: ret // CHECK: attributes #[[ATTR]] = { noinline } protocol Proto { func testit(x: Int32) -> Int32 } struct TestStruct : Proto { func testit(x: Int32) -> Int32 { var y = x * 2 y += 1 y *= x y += 1 y *= x y += 1 y *= x y += 1 y *= x y += 1 y *= x y += 1 return y } }
21.452381
124
0.589345
5ddccf4616426b22de0b56f69aa3ab661690e41d
6,822
// Document.swift // Copyright (c) 2015 Ce Zheng // // 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 libxml2 /// XML document which can be searched and queried. open class XMLDocument { // MARK: - Document Attributes /// The XML version. open fileprivate(set) lazy var version: String? = { return ^-^self.cDocument.pointee.version }() /// The string encoding for the document. This is NSUTF8StringEncoding if no encoding is set, or it cannot be calculated. open fileprivate(set) lazy var encoding: String.Encoding = { if let encodingName = ^-^self.cDocument.pointee.encoding { let encoding = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString?) if encoding != kCFStringEncodingInvalidId { return String.Encoding(rawValue: UInt(CFStringConvertEncodingToNSStringEncoding(encoding))) } } return String.Encoding.utf8 }() // MARK: - Accessing the Root Element /// The root element of the document. open fileprivate(set) var root: XMLElement? // MARK: - Accessing & Setting Document Formatters /// The formatter used to determine `numberValue` for elements in the document. By default, this is an `NSNumberFormatter` instance with `NSNumberFormatterDecimalStyle`. open lazy var numberFormatter: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .decimal return formatter }() /// The formatter used to determine `dateValue` for elements in the document. By default, this is an `NSDateFormatter` instance configured to accept ISO 8601 formatted timestamps. open lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" return formatter }() // MARK: - Creating XML Documents fileprivate let cDocument: xmlDocPtr /** Creates and returns an instance of XMLDocument from an XML string, throwing XMLError if an error occured while parsing the XML. - parameter string: The XML string. - parameter encoding: The string encoding. - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(string: String, encoding: String.Encoding = String.Encoding.utf8) throws { guard let cChars = string.cString(using: encoding) else { throw XMLError.invalidData } try self.init(cChars: cChars) } /** Creates and returns an instance of XMLDocument from XML data, throwing XMLError if an error occured while parsing the XML. - parameter data: The XML data. - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(data: Data) throws { let cChars = data.withUnsafeBytes { (bytes: UnsafePointer<Int8>) -> [CChar] in let buffer = UnsafeBufferPointer(start: bytes, count: data.count) return [CChar](buffer) } try self.init(cChars: cChars) } /** Creates and returns an instance of XMLDocument from C char array, throwing XMLError if an error occured while parsing the XML. - parameter cChars: cChars The XML data as C char array - throws: `XMLError` instance if an error occurred - returns: An `XMLDocument` with the contents of the specified XML string. */ public convenience init(cChars: [CChar]) throws { let options = Int32(XML_PARSE_NOWARNING.rawValue | XML_PARSE_NOERROR.rawValue | XML_PARSE_RECOVER.rawValue) try self.init(cChars: cChars, options: options) } fileprivate convenience init(cChars: [CChar], options: Int32) throws { guard let document = type(of: self).parse(cChars: cChars, size: cChars.count, options: options) else { throw XMLError.lastError(defaultError: .parserFailure) } xmlResetLastError() self.init(cDocument: document) } fileprivate class func parse(cChars: [CChar], size: Int, options: Int32) -> xmlDocPtr? { return xmlReadMemory(UnsafePointer(cChars), Int32(size), "", nil, options) } fileprivate init(cDocument: xmlDocPtr) { self.cDocument = cDocument if let cRoot = xmlDocGetRootElement(cDocument) { root = XMLElement(cNode: cRoot, document: self) } } deinit { xmlFreeDoc(cDocument) } // MARK: - XML Namespaces var defaultNamespaces = [String: String]() /** Define a prefix for a default namespace. - parameter prefix: The prefix name - parameter ns: The default namespace URI that declared in XML Document */ open func definePrefix(_ prefix: String, defaultNamespace ns: String) { defaultNamespaces[ns] = prefix } } extension XMLDocument: Equatable {} /** Determine whether two documents are the same - parameter lhs: XMLDocument on the left - parameter rhs: XMLDocument on the right - returns: whether lhs and rhs are equal */ public func ==(lhs: XMLDocument, rhs: XMLDocument) -> Bool { return lhs.cDocument == rhs.cDocument } /// HTML document which can be searched and queried. open class HTMLDocument: XMLDocument { // MARK: - Convenience Accessors /// HTML title of current document open var title: String? { return root?.firstChild(tag: "head")?.firstChild(tag: "title")?.stringValue } /// HTML head element of current document open var head: XMLElement? { return root?.firstChild(tag: "head") } /// HTML body element of current document open var body: XMLElement? { return root?.firstChild(tag: "body") } fileprivate override class func parse(cChars: [CChar], size: Int, options: Int32) -> xmlDocPtr? { return htmlReadMemory(UnsafePointer(cChars), Int32(size), "", nil, options) } }
35.905263
181
0.718264
61198f871291d7ca79e8bdf85b6bd4e1c6fba1f0
696
// // 4-Protocols default implementation.playground // Packt Progressional Swift Courseware // // Created by [email protected] on 8/17/17. // import UIKit protocol Employee { var name: String {get set} mutating func changeName(newName: String) } struct HourlyEmployee: Employee { var name: String mutating func changeName(newName: String) { name = newName } } struct Manager: Employee { var name: String mutating func changeName(newName: String) { name = newName } } var john = HourlyEmployee(name: "John Smith") var sarah = Manager(name: "Sarah Jones") print(john.name) john.changeName(newName: "John Smyth") print(john.name)
18.810811
54
0.692529
08ea96122eb4ba85875925e62751558a01f33601
4,694
// // This file is derived from QuantLib. The license of QuantLib is available online at <http://quantlib.org/license.shtml>. // // ActualActual.swift // SwiftDate // // Created by Helin Gai on 7/7/14. // Copyright (c) 2014 SHFuse. All rights reserved. // import Foundation public class ActualActual : DayCounter { public enum Convention { case ISMA, Bond, ISDA, Historical, Actual365 } class ISMA_Impl : DayCounter.Impl { override func name() -> String { return "Actual/Actual (ISMA)" } override func shortName() -> String { return "Actual/Actual" } override func dayCountFraction(date1 : Date, date2 : Date, referenceStartDate : Date = Date(), referenceEndDate : Date = Date()) -> Double { if (date1 == date2) { return 0.0 } if (date1 > date2) { return dayCountFraction(date2, date2: date1, referenceStartDate: referenceStartDate, referenceEndDate: referenceEndDate) } var refPeriodStart = (referenceStartDate != Date() ? referenceStartDate : date1) var refPeriodEnd = (referenceEndDate != Date() ? referenceEndDate : date2) var months = Int(0.5 + 12 * Double(refPeriodEnd - refPeriodStart) / 365.0) if (months == 0) { refPeriodStart = date1 refPeriodEnd = date1.addYears(1) months = 12 } let period = Double(months) / 12.0 if (date2 <= refPeriodEnd) { if (date1 >= refPeriodStart) { return period * Double(dayCount(date1, date2 : date2)) / Double(dayCount(refPeriodStart, date2 : refPeriodEnd)) } else { let prevRef = refPeriodStart.addMonths(months) if (date2 > refPeriodStart) { return dayCountFraction(date1, date2: refPeriodStart, referenceStartDate: prevRef, referenceEndDate: refPeriodStart) + dayCountFraction(refPeriodStart, date2: date2, referenceStartDate: refPeriodStart, referenceEndDate: refPeriodEnd) } else { return dayCountFraction(date1, date2: date2, referenceStartDate: prevRef, referenceEndDate: refPeriodStart) } } } else { var sum = dayCountFraction(date1, date2: refPeriodEnd, referenceStartDate: refPeriodStart, referenceEndDate: refPeriodEnd) var i = 0 var newRefStart = Date(), newRefEnd = Date() while true { newRefStart = refPeriodEnd.addMonths(months * i) newRefEnd = refPeriodEnd.addMonths(months * (i + 1)) if(date2 < newRefEnd) { break } else { sum += period i += 1 } } sum += dayCountFraction(newRefStart, date2: date2, referenceStartDate: newRefStart, referenceEndDate: newRefEnd) return sum } } } class ISDA_Impl : DayCounter.Impl { override func name() -> String { return "Actual/Actual (ISDA)" } override func shortName() -> String { return "Actual/Actual" } override func dayCountFraction(date1 : Date, date2 : Date, referenceStartDate : Date = Date(), referenceEndDate : Date = Date()) -> Double { if (date1 == date2) { return 0 } if (date1 > date2) { return dayCountFraction(date2, date2: date1, referenceStartDate: referenceStartDate, referenceEndDate: referenceEndDate) } let y1 = date1.year() let y2 = date2.year() let dib1 = (Date.isLeap(y1) ? 366.0 : 365.0) let dib2 = (Date.isLeap(y2) ? 366.0 : 365.0) var sum = Double(y2 - y1 - 1) sum += Double(dayCount(date1, date2: Date(year: y1 + 1, month: 1, day: 1))) / dib1 sum += Double(dayCount(Date(year: y2, month: 1, day: 1), date2: date2)) / dib2 return sum } } public init(convention : ActualActual.Convention = ActualActual.Convention.ISDA) { super.init() switch convention { case .ISMA, .Bond: impl = ActualActual.ISMA_Impl() case .ISDA, .Historical, .Actual365: impl = ActualActual.ISDA_Impl() } } }
40.465517
257
0.532808
e2df01360d5980ef6a69a19e91e11b8386115f55
1,521
// // UIImageView+Ex.swift // SWFrame // // Created by 杨建祥 on 2020/5/3. // import UIKit import QMUIKit import RxSwift import RxCocoa import Kingfisher public extension Reactive where Base: UIImageView { var imageSource: Binder<ImageSource?> { return Binder(self.base) { imageView, resource in imageView.isHidden = false if let image = resource as? UIImage { imageView.image = image } else if let url = resource as? URL { imageView.kf.setImage(with: url) } else { imageView.isHidden = true } } } func imageResource( placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil ) -> Binder<ImageSource?> { return Binder(self.base) { imageView, resource in imageView.isHidden = false if let image = resource as? UIImage { imageView.image = image } else if let url = resource as? URL { imageView.kf.setImage(with: url, placeholder: placeholder, options: options) } else { imageView.isHidden = true } } } // func imageResource(placeholder: Placeholder? = nil, options: KingfisherOptionsInfo? = nil) -> Binder<Resource?> { // return Binder(self.base) { imageView, resource in // imageView.kf.setImage(with: resource, placeholder: placeholder, options: options) // } // } }
29.25
119
0.571992
9b586b342f5c9c40d59ac4742121d1befad65a2d
2,246
/*: # 543. Diameter of Binary Tree Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. Example: Given a binary tree 1 / \ 2 3 / \ 4 5 Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. Note: The length of path between two nodes is represented by the number of edges between them. **Implement below function** /** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */ func diameterOfBinaryTree(_ root: TreeNode?) -> Int { } */ // Definition for a binary tree node. public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } /*: dfs **Time Complexity:** O(n) **Space Complexity:** O(h) */ class Solution { func diameterOfBinaryTree(_ root: TreeNode?) -> Int { var maxDiameter = 0 traverse(root, 0, &maxDiameter) return maxDiameter } func traverse(_ root: TreeNode?, _ currDepth: Int, _ maxDiameter: inout Int) -> Int { guard let root = root else { return currDepth } let left = traverse(root.left, currDepth, &maxDiameter) let right = traverse(root.right, currDepth, &maxDiameter) maxDiameter = max(left + right, maxDiameter) return max(left, right) + 1 } } /*: ## Test */ import XCTest class TestDiameterOfBinaryTree: XCTestCase { func testDiameterOfBinaryTree() { let node1 = TreeNode(1) let node2 = TreeNode(2) let node3 = TreeNode(3) let node4 = TreeNode(4) let node5 = TreeNode(5) node1.left = node2 node1.right = node3 node2.left = node4 node2.right = node5 let result = Solution().diameterOfBinaryTree(node1) XCTAssertEqual(result, 3) } } TestDiameterOfBinaryTree.defaultTestSuite.run()
20.796296
226
0.637133
46dd4447888324ce9228ab8f20b1a461101414dc
73,525
// // SignalSpec.swift // ReactiveSwift // // Created by Justin Spahr-Summers on 2015-01-23. // Copyright (c) 2015 GitHub. All rights reserved. // import Foundation import Dispatch import Result import Nimble import Quick @testable import ReactiveSwift class SignalSpec: QuickSpec { override func spec() { describe("init") { var testScheduler: TestScheduler! beforeEach { testScheduler = TestScheduler() } it("should run the generator immediately") { var didRunGenerator = false _ = Signal<AnyObject, NoError> { observer in didRunGenerator = true return nil } expect(didRunGenerator) == true } it("should forward events to observers") { let numbers = [ 1, 2, 5 ] let signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { for number in numbers { observer.send(value: number) } observer.sendCompleted() } return nil } var fromSignal: [Int] = [] var completed = false signal.observe { event in switch event { case let .value(number): fromSignal.append(number) case .completed: completed = true default: break } } expect(completed) == false expect(fromSignal).to(beEmpty()) testScheduler.run() expect(completed) == true expect(fromSignal) == numbers } it("should dispose of returned disposable upon error") { let disposable = SimpleDisposable() let signal: Signal<AnyObject, TestError> = Signal { observer in testScheduler.schedule { observer.send(error: TestError.default) } return disposable } var errored = false signal.observeFailed { _ in errored = true } expect(errored) == false expect(disposable.isDisposed) == false testScheduler.run() expect(errored) == true expect(disposable.isDisposed) == true } it("should dispose of returned disposable upon completion") { let disposable = SimpleDisposable() let signal: Signal<AnyObject, NoError> = Signal { observer in testScheduler.schedule { observer.sendCompleted() } return disposable } var completed = false signal.observeCompleted { completed = true } expect(completed) == false expect(disposable.isDisposed) == false testScheduler.run() expect(completed) == true expect(disposable.isDisposed) == true } it("should dispose of returned disposable upon interrupted") { let disposable = SimpleDisposable() let signal: Signal<AnyObject, NoError> = Signal { observer in testScheduler.schedule { observer.sendInterrupted() } return disposable } var interrupted = false signal.observeInterrupted { interrupted = true } expect(interrupted) == false expect(disposable.isDisposed) == false testScheduler.run() expect(interrupted) == true expect(disposable.isDisposed) == true } } describe("Signal.empty") { it("should interrupt its observers without emitting any value") { let signal = Signal<(), NoError>.empty var hasUnexpectedEventsEmitted = false var signalInterrupted = false signal.observe { event in switch event { case .value, .failed, .completed: hasUnexpectedEventsEmitted = true case .interrupted: signalInterrupted = true } } expect(hasUnexpectedEventsEmitted) == false expect(signalInterrupted) == true } } describe("Signal.pipe") { it("should forward events to observers") { let (signal, observer) = Signal<Int, NoError>.pipe() var fromSignal: [Int] = [] var completed = false signal.observe { event in switch event { case let .value(number): fromSignal.append(number) case .completed: completed = true default: break } } expect(fromSignal).to(beEmpty()) expect(completed) == false observer.send(value: 1) expect(fromSignal) == [ 1 ] observer.send(value: 2) expect(fromSignal) == [ 1, 2 ] expect(completed) == false observer.sendCompleted() expect(completed) == true } it("should dispose the supplied disposable when the signal terminates") { let disposable = SimpleDisposable() let (signal, observer) = Signal<(), NoError>.pipe(disposable: disposable) expect(disposable.isDisposed) == false observer.sendCompleted() expect(disposable.isDisposed) == true } context("memory") { it("should not crash allocating memory with a few observers") { let (signal, _) = Signal<Int, NoError>.pipe() #if os(Linux) func autoreleasepool(invoking code: () -> Void) { code() } #endif for _ in 0..<50 { autoreleasepool { let disposable = signal.observe { _ in } disposable!.dispose() } } } } } describe("interruption") { it("should not send events after sending an interrupted event") { let queue: DispatchQueue let counter = Atomic<Int>(0) if #available(macOS 10.10, *) { queue = DispatchQueue.global(qos: .userInitiated) } else { queue = DispatchQueue.global(priority: .high) } let (signal, observer) = Signal<Int, NoError>.pipe() var hasSlept = false var events: [Event<Int, NoError>] = [] // Used to synchronize the `interrupt` sender to only act after the // chosen observer has started sending its event, but before it is done. let semaphore = DispatchSemaphore(value: 0) signal.observe { event in if !hasSlept { semaphore.signal() // 100000 us = 0.1 s usleep(100000) hasSlept = true } events.append(event) } let group = DispatchGroup() DispatchQueue.concurrentPerform(iterations: 10) { index in queue.async(group: group) { observer.send(value: index) } if index == 0 { semaphore.wait() observer.sendInterrupted() } } group.wait() expect(events.count) == 2 if events.count >= 2 { expect(events[1].isTerminating) == true } } it("should interrupt concurrently") { let queue: DispatchQueue let counter = Atomic<Int>(0) let executionCounter = Atomic<Int>(0) if #available(macOS 10.10, *) { queue = DispatchQueue.global(qos: .userInitiated) } else { queue = DispatchQueue.global(priority: .high) } let iterations = 1000 let group = DispatchGroup() queue.async(group: group) { DispatchQueue.concurrentPerform(iterations: iterations) { _ in let (signal, observer) = Signal<(), NoError>.pipe() var isInterrupted = false signal.observeInterrupted { counter.modify { $0 += 1 } } // Used to synchronize the `value` sender and the `interrupt` // sender, giving a slight priority to the former. let semaphore = DispatchSemaphore(value: 0) queue.async(group: group) { semaphore.signal() observer.send(value: ()) executionCounter.modify { $0 += 1 } } queue.async(group: group) { semaphore.wait() observer.sendInterrupted() executionCounter.modify { $0 += 1 } } } } group.wait() expect(executionCounter.value) == iterations * 2 expect(counter.value).toEventually(equal(iterations), timeout: 5) } } describe("observe") { var testScheduler: TestScheduler! beforeEach { testScheduler = TestScheduler() } it("should stop forwarding events when disposed") { let disposable = SimpleDisposable() let signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { for number in [ 1, 2 ] { observer.send(value: number) } observer.sendCompleted() observer.send(value: 4) } return disposable } var fromSignal: [Int] = [] signal.observeValues { number in fromSignal.append(number) } expect(disposable.isDisposed) == false expect(fromSignal).to(beEmpty()) testScheduler.run() expect(disposable.isDisposed) == true expect(fromSignal) == [ 1, 2 ] } it("should not trigger side effects") { var runCount = 0 let signal: Signal<(), NoError> = Signal { observer in runCount += 1 return nil } expect(runCount) == 1 signal.observe(Observer<(), NoError>()) expect(runCount) == 1 } it("should release observer after termination") { weak var testStr: NSMutableString? let (signal, observer) = Signal<Int, NoError>.pipe() let test = { let innerStr = NSMutableString(string: "") signal.observeValues { value in innerStr.append("\(value)") } testStr = innerStr } test() observer.send(value: 1) expect(testStr) == "1" observer.send(value: 2) expect(testStr) == "12" observer.sendCompleted() expect(testStr).to(beNil()) } it("should release observer after interruption") { weak var testStr: NSMutableString? let (signal, observer) = Signal<Int, NoError>.pipe() let test = { let innerStr = NSMutableString(string: "") signal.observeValues { value in innerStr.append("\(value)") } testStr = innerStr } test() observer.send(value: 1) expect(testStr) == "1" observer.send(value: 2) expect(testStr) == "12" observer.sendInterrupted() expect(testStr).to(beNil()) } } describe("trailing closure") { it("receives next values") { var values = [Int]() let (signal, observer) = Signal<Int, NoError>.pipe() signal.observeValues { value in values.append(value) } observer.send(value: 1) expect(values) == [1] } it("receives results") { let (signal, observer) = Signal<Int, TestError>.pipe() var results: [Result<Int, TestError>] = [] signal.observeResult { results.append($0) } observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) observer.send(error: .default) observer.sendCompleted() expect(results).to(haveCount(4)) expect(results[0].value) == 1 expect(results[1].value) == 2 expect(results[2].value) == 3 expect(results[3].error) == .default } } describe("map") { it("should transform the values of the signal") { let (signal, observer) = Signal<Int, NoError>.pipe() let mappedSignal = signal.map { String($0 + 1) } var lastValue: String? mappedSignal.observeValues { lastValue = $0 return } expect(lastValue).to(beNil()) observer.send(value: 0) expect(lastValue) == "1" observer.send(value: 1) expect(lastValue) == "2" } } describe("mapError") { it("should transform the errors of the signal") { let (signal, observer) = Signal<Int, TestError>.pipe() let producerError = NSError(domain: "com.reactivecocoa.errordomain", code: 100, userInfo: nil) var error: NSError? signal .mapError { _ in producerError } .observeFailed { err in error = err } expect(error).to(beNil()) observer.send(error: TestError.default) expect(error) == producerError } } describe("lazyMap") { describe("with a scheduled binding") { var token: Lifetime.Token! var lifetime: Lifetime! var destination: [String] = [] var tupleSignal: Signal<(character: String, other: Int), NoError>! var tupleObserver: Signal<(character: String, other: Int), NoError>.Observer! var theLens: Signal<String, NoError>! var getterCounter: Int = 0 var lensScheduler: TestScheduler! var targetScheduler: TestScheduler! var target: BindingTarget<String>! beforeEach { destination = [] token = Lifetime.Token() lifetime = Lifetime(token) let (producer, observer) = Signal<(character: String, other: Int), NoError>.pipe() tupleSignal = producer tupleObserver = observer lensScheduler = TestScheduler() targetScheduler = TestScheduler() getterCounter = 0 theLens = tupleSignal.lazyMap(on: lensScheduler) { (tuple: (character: String, other: Int)) -> String in getterCounter += 1 return tuple.character } target = BindingTarget<String>(on: targetScheduler, lifetime: lifetime) { destination.append($0) } target <~ theLens } it("should not propagate values until scheduled") { // Send a value along tupleObserver.send(value: (character: "🎃", other: 42)) // The destination should not change value, and the getter // should not have evaluated yet, as neither has been scheduled expect(destination) == [] expect(getterCounter) == 0 // Advance both schedulers lensScheduler.advance() targetScheduler.advance() // The destination receives the previously-sent value, and the // getter obviously evaluated expect(destination) == ["🎃"] expect(getterCounter) == 1 } it("should evaluate the getter only when scheduled") { // Send a value along tupleObserver.send(value: (character: "🎃", other: 42)) // The destination should not change value, and the getter // should not have evaluated yet, as neither has been scheduled expect(destination) == [] expect(getterCounter) == 0 // When the getter's scheduler advances, the getter should // be evaluated, but the destination still shouldn't accept // the new value lensScheduler.advance() expect(getterCounter) == 1 expect(destination) == [] // Sending other values along shouldn't evaluate the getter tupleObserver.send(value: (character: "😾", other: 42)) tupleObserver.send(value: (character: "🍬", other: 13)) tupleObserver.send(value: (character: "👻", other: 17)) expect(getterCounter) == 1 expect(destination) == [] // Push the scheduler along for the lens, and the getter // should evaluate lensScheduler.advance() expect(getterCounter) == 2 // ...but the destination still won't receive the value expect(destination) == [] // Finally, pushing the target scheduler along will // propagate only the first and last values targetScheduler.advance() expect(getterCounter) == 2 expect(destination) == ["🎃", "👻"] } } } describe("filter") { it("should omit values from the signal") { let (signal, observer) = Signal<Int, NoError>.pipe() let mappedSignal = signal.filter { $0 % 2 == 0 } var lastValue: Int? mappedSignal.observeValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: 0) expect(lastValue) == 0 observer.send(value: 1) expect(lastValue) == 0 observer.send(value: 2) expect(lastValue) == 2 } } describe("filterMap") { it("should omit values from the signal that are nil after the transformation") { let (signal, observer) = Signal<String, NoError>.pipe() let mappedSignal: Signal<Int, NoError> = signal.filterMap { Int.init($0) } var lastValue: Int? mappedSignal.observeValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: "0") expect(lastValue) == 0 observer.send(value: "1") expect(lastValue) == 1 observer.send(value: "A") expect(lastValue) == 1 } it("should stop emiting values after an error") { let (signal, observer) = Signal<String, TestError>.pipe() let mappedSignal: Signal<Int, TestError> = signal.filterMap { Int.init($0) } var lastValue: Int? mappedSignal.observeResult { result in if let value = result.value { lastValue = value } } expect(lastValue).to(beNil()) observer.send(value: "0") expect(lastValue) == 0 observer.send(error: .default) observer.send(value: "1") expect(lastValue) == 0 } it("should stop emiting values after a complete") { let (signal, observer) = Signal<String, NoError>.pipe() let mappedSignal: Signal<Int, NoError> = signal.filterMap { Int.init($0) } var lastValue: Int? mappedSignal.observeValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: "0") expect(lastValue) == 0 observer.sendCompleted() observer.send(value: "1") expect(lastValue) == 0 } it("should send completed") { let (signal, observer) = Signal<String, NoError>.pipe() let mappedSignal: Signal<Int, NoError> = signal.filterMap { Int.init($0) } var completed: Bool = false mappedSignal.observeCompleted { completed = true } observer.sendCompleted() expect(completed) == true } it("should send failure") { let (signal, observer) = Signal<String, TestError>.pipe() let mappedSignal: Signal<Int, TestError> = signal.filterMap { Int.init($0) } var failure: TestError? mappedSignal.observeFailed { failure = $0 } observer.send(error: .error1) expect(failure) == .error1 } } describe("skipNil") { it("should forward only non-nil values") { let (signal, observer) = Signal<Int?, NoError>.pipe() let mappedSignal = signal.skipNil() var lastValue: Int? mappedSignal.observeValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: nil) expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue) == 1 observer.send(value: nil) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 } } describe("scan") { it("should incrementally accumulate a value") { let (baseSignal, observer) = Signal<String, NoError>.pipe() let signal = baseSignal.scan("", +) var lastValue: String? signal.observeValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: "a") expect(lastValue) == "a" observer.send(value: "bb") expect(lastValue) == "abb" } } describe("reduce") { it("should accumulate one value") { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let signal = baseSignal.reduce(1, +) var lastValue: Int? var completed = false signal.observe { event in switch event { case let .value(value): lastValue = value case .completed: completed = true default: break } } expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue).to(beNil()) expect(completed) == false observer.sendCompleted() expect(completed) == true expect(lastValue) == 4 } it("should send the initial value if none are received") { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let signal = baseSignal.reduce(1, +) var lastValue: Int? var completed = false signal.observe { event in switch event { case let .value(value): lastValue = value case .completed: completed = true default: break } } expect(lastValue).to(beNil()) expect(completed) == false observer.sendCompleted() expect(lastValue) == 1 expect(completed) == true } } describe("skip") { it("should skip initial values") { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let signal = baseSignal.skip(first: 1) var lastValue: Int? signal.observeValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue) == 2 } it("should not skip any values when 0") { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let signal = baseSignal.skip(first: 0) var lastValue: Int? signal.observeValues { lastValue = $0 } expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 } } describe("skipRepeats") { it("should skip duplicate Equatable values") { let (baseSignal, observer) = Signal<Bool, NoError>.pipe() let signal = baseSignal.skipRepeats() var values: [Bool] = [] signal.observeValues { values.append($0) } expect(values) == [] observer.send(value: true) expect(values) == [ true ] observer.send(value: true) expect(values) == [ true ] observer.send(value: false) expect(values) == [ true, false ] observer.send(value: true) expect(values) == [ true, false, true ] } it("should skip values according to a predicate") { let (baseSignal, observer) = Signal<String, NoError>.pipe() let signal = baseSignal.skipRepeats { $0.characters.count == $1.characters.count } var values: [String] = [] signal.observeValues { values.append($0) } expect(values) == [] observer.send(value: "a") expect(values) == [ "a" ] observer.send(value: "b") expect(values) == [ "a" ] observer.send(value: "cc") expect(values) == [ "a", "cc" ] observer.send(value: "d") expect(values) == [ "a", "cc", "d" ] } it("should not store strong reference to previously passed items") { var disposedItems: [Bool] = [] struct Item { let payload: Bool let disposable: ScopedDisposable<ActionDisposable> } func item(_ payload: Bool) -> Item { return Item( payload: payload, disposable: ScopedDisposable(ActionDisposable { disposedItems.append(payload) }) ) } let (baseSignal, observer) = Signal<Item, NoError>.pipe() baseSignal.skipRepeats { $0.payload == $1.payload }.observeValues { _ in } observer.send(value: item(true)) expect(disposedItems) == [] observer.send(value: item(false)) expect(disposedItems) == [ true ] observer.send(value: item(false)) expect(disposedItems) == [ true, false ] observer.send(value: item(true)) expect(disposedItems) == [ true, false, false ] observer.sendCompleted() expect(disposedItems) == [ true, false, false, true ] } } describe("uniqueValues") { it("should skip values that have been already seen") { let (baseSignal, observer) = Signal<String, NoError>.pipe() let signal = baseSignal.uniqueValues() var values: [String] = [] signal.observeValues { values.append($0) } expect(values) == [] observer.send(value: "a") expect(values) == [ "a" ] observer.send(value: "b") expect(values) == [ "a", "b" ] observer.send(value: "a") expect(values) == [ "a", "b" ] observer.send(value: "b") expect(values) == [ "a", "b" ] observer.send(value: "c") expect(values) == [ "a", "b", "c" ] observer.sendCompleted() expect(values) == [ "a", "b", "c" ] } } describe("skipWhile") { var signal: Signal<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var lastValue: Int? beforeEach { let (baseSignal, incomingObserver) = Signal<Int, NoError>.pipe() signal = baseSignal.skip { $0 < 2 } observer = incomingObserver lastValue = nil signal.observeValues { lastValue = $0 } } it("should skip while the predicate is true") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue) == 2 observer.send(value: 0) expect(lastValue) == 0 } it("should not skip any values when the predicate starts false") { expect(lastValue).to(beNil()) observer.send(value: 3) expect(lastValue) == 3 observer.send(value: 1) expect(lastValue) == 1 } } describe("skipUntil") { var signal: Signal<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var triggerObserver: Signal<(), NoError>.Observer! var lastValue: Int? = nil beforeEach { let (baseSignal, incomingObserver) = Signal<Int, NoError>.pipe() let (triggerSignal, incomingTriggerObserver) = Signal<(), NoError>.pipe() signal = baseSignal.skip(until: triggerSignal) observer = incomingObserver triggerObserver = incomingTriggerObserver lastValue = nil signal.observe { event in switch event { case let .value(value): lastValue = value default: break } } } it("should skip values until the trigger fires") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue).to(beNil()) triggerObserver.send(value: ()) observer.send(value: 0) expect(lastValue) == 0 } it("should skip values until the trigger completes") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue).to(beNil()) observer.send(value: 2) expect(lastValue).to(beNil()) triggerObserver.sendCompleted() observer.send(value: 0) expect(lastValue) == 0 } } describe("take") { it("should take initial values") { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let signal = baseSignal.take(first: 2) var lastValue: Int? var completed = false signal.observe { event in switch event { case let .value(value): lastValue = value case .completed: completed = true default: break } } expect(lastValue).to(beNil()) expect(completed) == false observer.send(value: 1) expect(lastValue) == 1 expect(completed) == false observer.send(value: 2) expect(lastValue) == 2 expect(completed) == true } it("should complete immediately after taking given number of values") { let numbers = [ 1, 2, 4, 4, 5 ] let testScheduler = TestScheduler() var signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { for number in numbers { observer.send(value: number) } } return nil } var completed = false signal = signal.take(first: numbers.count) signal.observeCompleted { completed = true } expect(completed) == false testScheduler.run() expect(completed) == true } it("should interrupt when 0") { let numbers = [ 1, 2, 4, 4, 5 ] let testScheduler = TestScheduler() let signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { for number in numbers { observer.send(value: number) } } return nil } var result: [Int] = [] var interrupted = false signal .take(first: 0) .observe { event in switch event { case let .value(number): result.append(number) case .interrupted: interrupted = true default: break } } expect(interrupted) == true testScheduler.run() expect(result).to(beEmpty()) } } describe("collect") { it("should collect all values") { let (original, observer) = Signal<Int, NoError>.pipe() let signal = original.collect() let expectedResult = [ 1, 2, 3 ] var result: [Int]? signal.observeValues { value in expect(result).to(beNil()) result = value } for number in expectedResult { observer.send(value: number) } expect(result).to(beNil()) observer.sendCompleted() expect(result) == expectedResult } it("should complete with an empty array if there are no values") { let (original, observer) = Signal<Int, NoError>.pipe() let signal = original.collect() var result: [Int]? signal.observeValues { result = $0 } expect(result).to(beNil()) observer.sendCompleted() expect(result) == [] } it("should forward errors") { let (original, observer) = Signal<Int, TestError>.pipe() let signal = original.collect() var error: TestError? signal.observeFailed { error = $0 } expect(error).to(beNil()) observer.send(error: .default) expect(error) == TestError.default } it("should collect an exact count of values") { let (original, observer) = Signal<Int, NoError>.pipe() let signal = original.collect(count: 3) var observedValues: [[Int]] = [] signal.observeValues { value in observedValues.append(value) } var expectation: [[Int]] = [] for i in 1...7 { observer.send(value: i) if i % 3 == 0 { expectation.append([Int]((i - 2)...i)) expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC() } else { expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC() } } observer.sendCompleted() expectation.append([7]) expect(observedValues._bridgeToObjectiveC()) == expectation._bridgeToObjectiveC() } it("should collect values until it matches a certain value") { let (original, observer) = Signal<Int, NoError>.pipe() let signal = original.collect { _, value in value != 5 } var expectedValues = [ [5, 5], [42, 5] ] signal.observeValues { value in expect(value) == expectedValues.removeFirst() } signal.observeCompleted { expect(expectedValues._bridgeToObjectiveC()) == [] } expectedValues .flatMap { $0 } .forEach(observer.send(value:)) observer.sendCompleted() } it("should collect values until it matches a certain condition on values") { let (original, observer) = Signal<Int, NoError>.pipe() let signal = original.collect { values in values.reduce(0, +) == 10 } var expectedValues = [ [1, 2, 3, 4], [5, 6, 7, 8, 9] ] signal.observeValues { value in expect(value) == expectedValues.removeFirst() } signal.observeCompleted { expect(expectedValues._bridgeToObjectiveC()) == [] } expectedValues .flatMap { $0 } .forEach(observer.send(value:)) observer.sendCompleted() } } describe("takeUntil") { var signal: Signal<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var triggerObserver: Signal<(), NoError>.Observer! var lastValue: Int? = nil var completed: Bool = false beforeEach { let (baseSignal, incomingObserver) = Signal<Int, NoError>.pipe() let (triggerSignal, incomingTriggerObserver) = Signal<(), NoError>.pipe() signal = baseSignal.take(until: triggerSignal) observer = incomingObserver triggerObserver = incomingTriggerObserver lastValue = nil completed = false signal.observe { event in switch event { case let .value(value): lastValue = value case .completed: completed = true default: break } } } it("should take values until the trigger fires") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 expect(completed) == false triggerObserver.send(value: ()) expect(completed) == true } it("should take values until the trigger completes") { expect(lastValue).to(beNil()) observer.send(value: 1) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 expect(completed) == false triggerObserver.sendCompleted() expect(completed) == true } it("should complete if the trigger fires immediately") { expect(lastValue).to(beNil()) expect(completed) == false triggerObserver.send(value: ()) expect(completed) == true expect(lastValue).to(beNil()) } } describe("takeUntilReplacement") { var signal: Signal<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var replacementObserver: Signal<Int, NoError>.Observer! var lastValue: Int? = nil var completed: Bool = false beforeEach { let (baseSignal, incomingObserver) = Signal<Int, NoError>.pipe() let (replacementSignal, incomingReplacementObserver) = Signal<Int, NoError>.pipe() signal = baseSignal.take(untilReplacement: replacementSignal) observer = incomingObserver replacementObserver = incomingReplacementObserver lastValue = nil completed = false signal.observe { event in switch event { case let .value(value): lastValue = value case .completed: completed = true default: break } } } it("should take values from the original then the replacement") { expect(lastValue).to(beNil()) expect(completed) == false observer.send(value: 1) expect(lastValue) == 1 observer.send(value: 2) expect(lastValue) == 2 replacementObserver.send(value: 3) expect(lastValue) == 3 expect(completed) == false observer.send(value: 4) expect(lastValue) == 3 expect(completed) == false replacementObserver.send(value: 5) expect(lastValue) == 5 expect(completed) == false replacementObserver.sendCompleted() expect(completed) == true } } describe("takeWhile") { var signal: Signal<Int, NoError>! var observer: Signal<Int, NoError>.Observer! beforeEach { let (baseSignal, incomingObserver) = Signal<Int, NoError>.pipe() signal = baseSignal.take { $0 <= 4 } observer = incomingObserver } it("should take while the predicate is true") { var latestValue: Int! var completed = false signal.observe { event in switch event { case let .value(value): latestValue = value case .completed: completed = true default: break } } for value in -1...4 { observer.send(value: value) expect(latestValue) == value expect(completed) == false } observer.send(value: 5) expect(latestValue) == 4 expect(completed) == true } it("should complete if the predicate starts false") { var latestValue: Int? var completed = false signal.observe { event in switch event { case let .value(value): latestValue = value case .completed: completed = true default: break } } observer.send(value: 5) expect(latestValue).to(beNil()) expect(completed) == true } } describe("observeOn") { it("should send events on the given scheduler") { let testScheduler = TestScheduler() let (signal, observer) = Signal<Int, NoError>.pipe() var result: [Int] = [] signal .observe(on: testScheduler) .observeValues { result.append($0) } observer.send(value: 1) observer.send(value: 2) expect(result).to(beEmpty()) testScheduler.run() expect(result) == [ 1, 2 ] } } describe("delay") { it("should send events on the given scheduler after the interval") { let testScheduler = TestScheduler() let signal: Signal<Int, NoError> = Signal { observer in testScheduler.schedule { observer.send(value: 1) } testScheduler.schedule(after: .seconds(5)) { observer.send(value: 2) observer.sendCompleted() } return nil } var result: [Int] = [] var completed = false signal .delay(10, on: testScheduler) .observe { event in switch event { case let .value(number): result.append(number) case .completed: completed = true default: break } } testScheduler.advance(by: .seconds(4)) // send initial value expect(result).to(beEmpty()) testScheduler.advance(by: .seconds(10)) // send second value and receive first expect(result) == [ 1 ] expect(completed) == false testScheduler.advance(by: .seconds(10)) // send second value and receive first expect(result) == [ 1, 2 ] expect(completed) == true } it("should schedule errors immediately") { let testScheduler = TestScheduler() let signal: Signal<Int, TestError> = Signal { observer in testScheduler.schedule { observer.send(error: TestError.default) } return nil } var errored = false signal .delay(10, on: testScheduler) .observeFailed { _ in errored = true } testScheduler.advance() expect(errored) == true } } describe("throttle") { var scheduler: TestScheduler! var observer: Signal<Int, NoError>.Observer! var signal: Signal<Int, NoError>! beforeEach { scheduler = TestScheduler() let (baseSignal, baseObserver) = Signal<Int, NoError>.pipe() observer = baseObserver signal = baseSignal.throttle(1, on: scheduler) expect(signal).notTo(beNil()) } it("should send values on the given scheduler at no less than the interval") { var values: [Int] = [] signal.observeValues { value in values.append(value) } expect(values) == [] observer.send(value: 0) expect(values) == [] scheduler.advance() expect(values) == [ 0 ] observer.send(value: 1) observer.send(value: 2) expect(values) == [ 0 ] scheduler.advance(by: .milliseconds(1500)) expect(values) == [ 0, 2 ] scheduler.advance(by: .seconds(3)) expect(values) == [ 0, 2 ] observer.send(value: 3) expect(values) == [ 0, 2 ] scheduler.advance() expect(values) == [ 0, 2, 3 ] observer.send(value: 4) observer.send(value: 5) scheduler.advance() expect(values) == [ 0, 2, 3 ] scheduler.rewind(by: .seconds(2)) expect(values) == [ 0, 2, 3 ] observer.send(value: 6) scheduler.advance() expect(values) == [ 0, 2, 3, 6 ] observer.send(value: 7) observer.send(value: 8) scheduler.advance() expect(values) == [ 0, 2, 3, 6 ] scheduler.run() expect(values) == [ 0, 2, 3, 6, 8 ] } it("should schedule completion immediately") { var values: [Int] = [] var completed = false signal.observe { event in switch event { case let .value(value): values.append(value) case .completed: completed = true default: break } } observer.send(value: 0) scheduler.advance() expect(values) == [ 0 ] observer.send(value: 1) observer.sendCompleted() expect(completed) == false scheduler.advance() expect(values) == [ 0 ] expect(completed) == true scheduler.run() expect(values) == [ 0 ] expect(completed) == true } } describe("throttle while") { var scheduler: ImmediateScheduler! var shouldThrottle: MutableProperty<Bool>! var observer: Signal<Int, NoError>.Observer! var signal: Signal<Int, NoError>! beforeEach { scheduler = ImmediateScheduler() shouldThrottle = MutableProperty(false) let (baseSignal, baseObserver) = Signal<Int, NoError>.pipe() observer = baseObserver signal = baseSignal.throttle(while: shouldThrottle, on: scheduler) expect(signal).notTo(beNil()) } it("passes through unthrottled values") { var values: [Int] = [] signal.observeValues { values.append($0) } observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) expect(values) == [1, 2, 3] } it("emits the latest throttled value when resumed") { var values: [Int] = [] signal.observeValues { values.append($0) } shouldThrottle.value = true observer.send(value: 1) observer.send(value: 2) shouldThrottle.value = false expect(values) == [2] } it("continues sending values after being resumed") { var values: [Int] = [] signal.observeValues { values.append($0) } shouldThrottle.value = true observer.send(value: 1) shouldThrottle.value = false observer.send(value: 2) observer.send(value: 3) expect(values) == [1, 2, 3] } it("stays throttled if the property completes while throttled") { var values: [Int] = [] signal.observeValues { values.append($0) } shouldThrottle.value = false observer.send(value: 1) shouldThrottle.value = true observer.send(value: 2) shouldThrottle = nil observer.send(value: 3) expect(values) == [1] } it("stays resumed if the property completes while resumed") { var values: [Int] = [] signal.observeValues { values.append($0) } shouldThrottle.value = true observer.send(value: 1) shouldThrottle.value = false observer.send(value: 2) shouldThrottle = nil observer.send(value: 3) expect(values) == [1, 2, 3] } it("doesn't extend the lifetime of the throttle property") { var completed = false shouldThrottle.lifetime.observeEnded { completed = true } observer.send(value: 1) shouldThrottle = nil expect(completed) == true } } describe("debounce") { var scheduler: TestScheduler! var observer: Signal<Int, NoError>.Observer! var signal: Signal<Int, NoError>! beforeEach { scheduler = TestScheduler() let (baseSignal, baseObserver) = Signal<Int, NoError>.pipe() observer = baseObserver signal = baseSignal.debounce(1, on: scheduler) expect(signal).notTo(beNil()) } it("should send values on the given scheduler once the interval has passed since the last value was sent") { var values: [Int] = [] signal.observeValues { value in values.append(value) } expect(values) == [] observer.send(value: 0) expect(values) == [] scheduler.advance() expect(values) == [] observer.send(value: 1) observer.send(value: 2) expect(values) == [] scheduler.advance(by: .milliseconds(1500)) expect(values) == [ 2 ] scheduler.advance(by: .seconds(3)) expect(values) == [ 2 ] observer.send(value: 3) expect(values) == [ 2 ] scheduler.advance() expect(values) == [ 2 ] observer.send(value: 4) observer.send(value: 5) scheduler.advance() expect(values) == [ 2 ] scheduler.run() expect(values) == [ 2, 5 ] } it("should schedule completion immediately") { var values: [Int] = [] var completed = false signal.observe { event in switch event { case let .value(value): values.append(value) case .completed: completed = true default: break } } observer.send(value: 0) scheduler.advance() expect(values) == [] observer.send(value: 1) observer.sendCompleted() expect(completed) == false scheduler.advance() expect(values) == [] expect(completed) == true scheduler.run() expect(values) == [] expect(completed) == true } } describe("sampleWith") { var sampledSignal: Signal<(Int, String), NoError>! var observer: Signal<Int, NoError>.Observer! var samplerObserver: Signal<String, NoError>.Observer! beforeEach { let (signal, incomingObserver) = Signal<Int, NoError>.pipe() let (sampler, incomingSamplerObserver) = Signal<String, NoError>.pipe() sampledSignal = signal.sample(with: sampler) observer = incomingObserver samplerObserver = incomingSamplerObserver } it("should forward the latest value when the sampler fires") { var result: [String] = [] sampledSignal.observeValues { (left, right) in result.append("\(left)\(right)") } observer.send(value: 1) observer.send(value: 2) samplerObserver.send(value: "a") expect(result) == [ "2a" ] } it("should do nothing if sampler fires before signal receives value") { var result: [String] = [] sampledSignal.observeValues { (left, right) in result.append("\(left)\(right)") } samplerObserver.send(value: "a") expect(result).to(beEmpty()) } it("should send lates value with sampler value multiple times when sampler fires multiple times") { var result: [String] = [] sampledSignal.observeValues { (left, right) in result.append("\(left)\(right)") } observer.send(value: 1) samplerObserver.send(value: "a") samplerObserver.send(value: "b") expect(result) == [ "1a", "1b" ] } it("should complete when both inputs have completed") { var completed = false sampledSignal.observeCompleted { completed = true } observer.sendCompleted() expect(completed) == false samplerObserver.sendCompleted() expect(completed) == true } } describe("sampleOn") { var sampledSignal: Signal<Int, NoError>! var observer: Signal<Int, NoError>.Observer! var samplerObserver: Signal<(), NoError>.Observer! beforeEach { let (signal, incomingObserver) = Signal<Int, NoError>.pipe() let (sampler, incomingSamplerObserver) = Signal<(), NoError>.pipe() sampledSignal = signal.sample(on: sampler) observer = incomingObserver samplerObserver = incomingSamplerObserver } it("should forward the latest value when the sampler fires") { var result: [Int] = [] sampledSignal.observeValues { result.append($0) } observer.send(value: 1) observer.send(value: 2) samplerObserver.send(value: ()) expect(result) == [ 2 ] } it("should do nothing if sampler fires before signal receives value") { var result: [Int] = [] sampledSignal.observeValues { result.append($0) } samplerObserver.send(value: ()) expect(result).to(beEmpty()) } it("should send lates value multiple times when sampler fires multiple times") { var result: [Int] = [] sampledSignal.observeValues { result.append($0) } observer.send(value: 1) samplerObserver.send(value: ()) samplerObserver.send(value: ()) expect(result) == [ 1, 1 ] } it("should complete when both inputs have completed") { var completed = false sampledSignal.observeCompleted { completed = true } observer.sendCompleted() expect(completed) == false samplerObserver.sendCompleted() expect(completed) == true } } describe("withLatest(from: signal)") { var withLatestSignal: Signal<(Int, String), NoError>! var observer: Signal<Int, NoError>.Observer! var sampleeObserver: Signal<String, NoError>.Observer! beforeEach { let (signal, incomingObserver) = Signal<Int, NoError>.pipe() let (samplee, incomingSampleeObserver) = Signal<String, NoError>.pipe() withLatestSignal = signal.withLatest(from: samplee) observer = incomingObserver sampleeObserver = incomingSampleeObserver } it("should forward the latest value when the receiver fires") { var result: [String] = [] withLatestSignal.observeValues { (left, right) in result.append("\(left)\(right)") } sampleeObserver.send(value: "a") sampleeObserver.send(value: "b") observer.send(value: 1) expect(result) == [ "1b" ] } it("should do nothing if receiver fires before samplee sends value") { var result: [String] = [] withLatestSignal.observeValues { (left, right) in result.append("\(left)\(right)") } observer.send(value: 1) expect(result).to(beEmpty()) } it("should send latest value with samplee value multiple times when receiver fires multiple times") { var result: [String] = [] withLatestSignal.observeValues { (left, right) in result.append("\(left)\(right)") } sampleeObserver.send(value: "a") observer.send(value: 1) observer.send(value: 2) expect(result) == [ "1a", "2a" ] } it("should complete when receiver has completed") { var completed = false withLatestSignal.observeCompleted { completed = true } sampleeObserver.sendCompleted() expect(completed) == false observer.sendCompleted() expect(completed) == true } it("should not affect when samplee has completed") { var event: Event<(Int, String), NoError>? = nil withLatestSignal.observe { event = $0 } sampleeObserver.sendCompleted() expect(event).to(beNil()) } it("should not affect when samplee has interrupted") { var event: Event<(Int, String), NoError>? = nil withLatestSignal.observe { event = $0 } sampleeObserver.sendInterrupted() expect(event).to(beNil()) } } describe("withLatest(from: producer)") { var withLatestSignal: Signal<(Int, String), NoError>! var observer: Signal<Int, NoError>.Observer! var sampleeObserver: Signal<String, NoError>.Observer! beforeEach { let (signal, incomingObserver) = Signal<Int, NoError>.pipe() let (samplee, incomingSampleeObserver) = SignalProducer<String, NoError>.pipe() withLatestSignal = signal.withLatest(from: samplee) observer = incomingObserver sampleeObserver = incomingSampleeObserver } it("should forward the latest value when the receiver fires") { var result: [String] = [] withLatestSignal.observeValues { (left, right) in result.append("\(left)\(right)") } sampleeObserver.send(value: "a") sampleeObserver.send(value: "b") observer.send(value: 1) expect(result) == [ "1b" ] } it("should do nothing if receiver fires before samplee sends value") { var result: [String] = [] withLatestSignal.observeValues { (left, right) in result.append("\(left)\(right)") } observer.send(value: 1) expect(result).to(beEmpty()) } it("should send latest value with samplee value multiple times when receiver fires multiple times") { var result: [String] = [] withLatestSignal.observeValues { (left, right) in result.append("\(left)\(right)") } sampleeObserver.send(value: "a") observer.send(value: 1) observer.send(value: 2) expect(result) == [ "1a", "2a" ] } it("should complete when receiver has completed") { var completed = false withLatestSignal.observeCompleted { completed = true } observer.sendCompleted() expect(completed) == true } it("should not affect when samplee has completed") { var event: Event<(Int, String), NoError>? = nil withLatestSignal.observe { event = $0 } sampleeObserver.sendCompleted() expect(event).to(beNil()) } it("should not affect when samplee has interrupted") { var event: Event<(Int, String), NoError>? = nil withLatestSignal.observe { event = $0 } sampleeObserver.sendInterrupted() expect(event).to(beNil()) } } describe("combineLatestWith") { var combinedSignal: Signal<(Int, Double), NoError>! var observer: Signal<Int, NoError>.Observer! var otherObserver: Signal<Double, NoError>.Observer! beforeEach { let (signal, incomingObserver) = Signal<Int, NoError>.pipe() let (otherSignal, incomingOtherObserver) = Signal<Double, NoError>.pipe() combinedSignal = signal.combineLatest(with: otherSignal) observer = incomingObserver otherObserver = incomingOtherObserver } it("should forward the latest values from both inputs") { var latest: (Int, Double)? combinedSignal.observeValues { latest = $0 } observer.send(value: 1) expect(latest).to(beNil()) // is there a better way to test tuples? otherObserver.send(value: 1.5) expect(latest?.0) == 1 expect(latest?.1) == 1.5 observer.send(value: 2) expect(latest?.0) == 2 expect(latest?.1) == 1.5 } it("should complete when both inputs have completed") { var completed = false combinedSignal.observeCompleted { completed = true } observer.sendCompleted() expect(completed) == false otherObserver.sendCompleted() expect(completed) == true } } describe("zipWith") { var leftObserver: Signal<Int, NoError>.Observer! var rightObserver: Signal<String, NoError>.Observer! var zipped: Signal<(Int, String), NoError>! beforeEach { let (leftSignal, incomingLeftObserver) = Signal<Int, NoError>.pipe() let (rightSignal, incomingRightObserver) = Signal<String, NoError>.pipe() leftObserver = incomingLeftObserver rightObserver = incomingRightObserver zipped = leftSignal.zip(with: rightSignal) } it("should combine pairs") { var result: [String] = [] zipped.observeValues { (left, right) in result.append("\(left)\(right)") } leftObserver.send(value: 1) leftObserver.send(value: 2) expect(result) == [] rightObserver.send(value: "foo") expect(result) == [ "1foo" ] leftObserver.send(value: 3) rightObserver.send(value: "bar") expect(result) == [ "1foo", "2bar" ] rightObserver.send(value: "buzz") expect(result) == [ "1foo", "2bar", "3buzz" ] rightObserver.send(value: "fuzz") expect(result) == [ "1foo", "2bar", "3buzz" ] leftObserver.send(value: 4) expect(result) == [ "1foo", "2bar", "3buzz", "4fuzz" ] } it("should complete when the shorter signal has completed") { var result: [String] = [] var completed = false zipped.observe { event in switch event { case let .value(left, right): result.append("\(left)\(right)") case .completed: completed = true default: break } } expect(completed) == false leftObserver.send(value: 0) leftObserver.sendCompleted() expect(completed) == false expect(result) == [] rightObserver.send(value: "foo") expect(completed) == true expect(result) == [ "0foo" ] } it("should complete when both signal have completed") { var result: [String] = [] var completed = false zipped.observe { event in switch event { case let .value(left, right): result.append("\(left)\(right)") case .completed: completed = true default: break } } expect(completed) == false leftObserver.send(value: 0) leftObserver.sendCompleted() expect(completed) == false expect(result) == [] rightObserver.sendCompleted() expect(result) == [ ] } it("should complete and drop unpaired pending values when both signal have completed") { var result: [String] = [] var completed = false zipped.observe { event in switch event { case let .value(left, right): result.append("\(left)\(right)") case .completed: completed = true default: break } } expect(completed) == false leftObserver.send(value: 0) leftObserver.send(value: 1) leftObserver.send(value: 2) leftObserver.send(value: 3) leftObserver.sendCompleted() expect(completed) == false expect(result) == [] rightObserver.send(value: "foo") rightObserver.send(value: "bar") rightObserver.sendCompleted() expect(result) == ["0foo", "1bar"] } } describe("materialize") { it("should reify events from the signal") { let (signal, observer) = Signal<Int, TestError>.pipe() var latestEvent: Event<Int, TestError>? signal .materialize() .observeValues { latestEvent = $0 } observer.send(value: 2) expect(latestEvent).toNot(beNil()) if let latestEvent = latestEvent { switch latestEvent { case let .value(value): expect(value) == 2 default: fail() } } observer.send(error: TestError.default) if let latestEvent = latestEvent { switch latestEvent { case .failed: () default: fail() } } } } describe("dematerialize") { typealias IntEvent = Event<Int, TestError> var observer: Signal<IntEvent, NoError>.Observer! var dematerialized: Signal<Int, TestError>! beforeEach { let (signal, incomingObserver) = Signal<IntEvent, NoError>.pipe() observer = incomingObserver dematerialized = signal.dematerialize() } it("should send values for Value events") { var result: [Int] = [] dematerialized .assumeNoErrors() .observeValues { result.append($0) } expect(result).to(beEmpty()) observer.send(value: .value(2)) expect(result) == [ 2 ] observer.send(value: .value(4)) expect(result) == [ 2, 4 ] } it("should error out for Error events") { var errored = false dematerialized.observeFailed { _ in errored = true } expect(errored) == false observer.send(value: .failed(TestError.default)) expect(errored) == true } it("should complete early for Completed events") { var completed = false dematerialized.observeCompleted { completed = true } expect(completed) == false observer.send(value: IntEvent.completed) expect(completed) == true } } describe("takeLast") { var observer: Signal<Int, TestError>.Observer! var lastThree: Signal<Int, TestError>! beforeEach { let (signal, incomingObserver) = Signal<Int, TestError>.pipe() observer = incomingObserver lastThree = signal.take(last: 3) } it("should send the last N values upon completion") { var result: [Int] = [] lastThree .assumeNoErrors() .observeValues { result.append($0) } observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) observer.send(value: 4) expect(result).to(beEmpty()) observer.sendCompleted() expect(result) == [ 2, 3, 4 ] } it("should send less than N values if not enough were received") { var result: [Int] = [] lastThree .assumeNoErrors() .observeValues { result.append($0) } observer.send(value: 1) observer.send(value: 2) observer.sendCompleted() expect(result) == [ 1, 2 ] } it("should send nothing when errors") { var result: [Int] = [] var errored = false lastThree.observe { event in switch event { case let .value(value): result.append(value) case .failed: errored = true default: break } } observer.send(value: 1) observer.send(value: 2) observer.send(value: 3) expect(errored) == false observer.send(error: TestError.default) expect(errored) == true expect(result).to(beEmpty()) } } describe("timeoutWithError") { var testScheduler: TestScheduler! var signal: Signal<Int, TestError>! var observer: Signal<Int, TestError>.Observer! beforeEach { testScheduler = TestScheduler() let (baseSignal, incomingObserver) = Signal<Int, TestError>.pipe() signal = baseSignal.timeout(after: 2, raising: TestError.default, on: testScheduler) observer = incomingObserver } it("should complete if within the interval") { var completed = false var errored = false signal.observe { event in switch event { case .completed: completed = true case .failed: errored = true default: break } } testScheduler.schedule(after: .seconds(1)) { observer.sendCompleted() } expect(completed) == false expect(errored) == false testScheduler.run() expect(completed) == true expect(errored) == false } it("should error if not completed before the interval has elapsed") { var completed = false var errored = false signal.observe { event in switch event { case .completed: completed = true case .failed: errored = true default: break } } testScheduler.schedule(after: .seconds(3)) { observer.sendCompleted() } expect(completed) == false expect(errored) == false testScheduler.run() expect(completed) == false expect(errored) == true } it("should be available for NoError") { let signal: Signal<Int, TestError> = Signal<Int, NoError>.never .timeout(after: 2, raising: TestError.default, on: testScheduler) _ = signal } } describe("attempt") { it("should forward original values upon success") { let (baseSignal, observer) = Signal<Int, TestError>.pipe() let signal = baseSignal.attempt { _ in return .success() } var current: Int? signal .assumeNoErrors() .observeValues { value in current = value } for value in 1...5 { observer.send(value: value) expect(current) == value } } it("should error if an attempt fails") { let (baseSignal, observer) = Signal<Int, TestError>.pipe() let signal = baseSignal.attempt { _ in return .failure(.default) } var error: TestError? signal.observeFailed { err in error = err } observer.send(value: 42) expect(error) == TestError.default } } describe("attempt throws") { it("should forward original values upon success") { let (baseSignal, observer) = Signal<Int, AnyError>.pipe() let signal = baseSignal.attempt { _ in _ = try operation(value: 1) } var current: Int? signal .assumeNoErrors() .observeValues { value in current = value } for value in 1...5 { observer.send(value: value) expect(current) == value } } it("should error if an attempt fails") { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let signal = baseSignal.attempt { _ in _ = try operation(value: nil) as Int } var error: TestError? signal.observeFailed { err in error = err.error as? TestError } observer.send(value: 42) expect(error) == TestError.default } it("should allow throwing closures with NoError") { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let signal = baseSignal.attempt { _ in _ = try operation(value: 1) } var value: Int? signal.observeResult { value = $0.value } observer.send(value: 42) expect(value) == 42 } } describe("attemptMap") { it("should forward mapped values upon success") { let (baseSignal, observer) = Signal<Int, TestError>.pipe() let signal = baseSignal.attemptMap { num -> Result<Bool, TestError> in return .success(num % 2 == 0) } var even: Bool? signal .assumeNoErrors() .observeValues { value in even = value } observer.send(value: 1) expect(even) == false observer.send(value: 2) expect(even) == true } it("should error if a mapping fails") { let (baseSignal, observer) = Signal<Int, TestError>.pipe() let signal = baseSignal.attemptMap { _ -> Result<Bool, TestError> in return .failure(.default) } var error: TestError? signal.observeFailed { err in error = err } observer.send(value: 42) expect(error) == TestError.default } } describe("attemptMap throws") { it("should forward mapped values upon success") { let (baseSignal, observer) = Signal<Int, AnyError>.pipe() let signal = baseSignal.attemptMap { num -> Bool in try operation(value: num % 2 == 0) } var even: Bool? signal .assumeNoErrors() .observeValues { value in even = value } observer.send(value: 1) expect(even) == false observer.send(value: 2) expect(even) == true } it("should error if a mapping fails") { let (baseSignal, observer) = Signal<Int, AnyError>.pipe() let signal = baseSignal.attemptMap { _ -> Bool in try operation(value: nil) } var error: TestError? signal.observeFailed { err in error = err.error as? TestError } observer.send(value: 42) expect(error) == TestError.default } it("should allow throwing closures with NoError") { let (baseSignal, observer) = Signal<Int, NoError>.pipe() let signal = baseSignal.attemptMap { num in try operation(value: num % 2 == 0) } var value: Bool? signal.observeResult { value = $0.value } observer.send(value: 2) expect(value) == true } } describe("combinePrevious") { var observer: Signal<Int, NoError>.Observer! let initialValue: Int = 0 var latestValues: (Int, Int)? beforeEach { latestValues = nil let (signal, baseObserver) = Signal<Int, NoError>.pipe() observer = baseObserver signal.combinePrevious(initialValue).observeValues { latestValues = $0 } } it("should forward the latest value with previous value") { expect(latestValues).to(beNil()) observer.send(value: 1) expect(latestValues?.0) == initialValue expect(latestValues?.1) == 1 observer.send(value: 2) expect(latestValues?.0) == 1 expect(latestValues?.1) == 2 } } describe("combineLatest") { var signalA: Signal<Int, NoError>! var signalB: Signal<Int, NoError>! var signalC: Signal<Int, NoError>! var observerA: Signal<Int, NoError>.Observer! var observerB: Signal<Int, NoError>.Observer! var observerC: Signal<Int, NoError>.Observer! var combinedValues: [Int]? var completed: Bool! beforeEach { combinedValues = nil completed = false let (baseSignalA, baseObserverA) = Signal<Int, NoError>.pipe() let (baseSignalB, baseObserverB) = Signal<Int, NoError>.pipe() let (baseSignalC, baseObserverC) = Signal<Int, NoError>.pipe() signalA = baseSignalA signalB = baseSignalB signalC = baseSignalC observerA = baseObserverA observerB = baseObserverB observerC = baseObserverC } let combineLatestExampleName = "combineLatest examples" sharedExamples(combineLatestExampleName) { it("should forward the latest values from all inputs"){ expect(combinedValues).to(beNil()) observerA.send(value: 0) observerB.send(value: 1) observerC.send(value: 2) expect(combinedValues) == [0, 1, 2] observerA.send(value: 10) expect(combinedValues) == [10, 1, 2] } it("should not forward the latest values before all inputs"){ expect(combinedValues).to(beNil()) observerA.send(value: 0) expect(combinedValues).to(beNil()) observerB.send(value: 1) expect(combinedValues).to(beNil()) observerC.send(value: 2) expect(combinedValues) == [0, 1, 2] } it("should complete when all inputs have completed"){ expect(completed) == false observerA.sendCompleted() observerB.sendCompleted() expect(completed) == false observerC.sendCompleted() expect(completed) == true } } describe("tuple") { beforeEach { Signal.combineLatest(signalA, signalB, signalC) .observe { event in switch event { case let .value(value): combinedValues = [value.0, value.1, value.2] case .completed: completed = true default: break } } } itBehavesLike(combineLatestExampleName) } describe("sequence") { beforeEach { Signal.combineLatest([signalA, signalB, signalC]) .observe { event in switch event { case let .value(values): combinedValues = values case .completed: completed = true default: break } } } itBehavesLike(combineLatestExampleName) } } describe("zip") { var signalA: Signal<Int, NoError>! var signalB: Signal<Int, NoError>! var signalC: Signal<Int, NoError>! var observerA: Signal<Int, NoError>.Observer! var observerB: Signal<Int, NoError>.Observer! var observerC: Signal<Int, NoError>.Observer! var zippedValues: [Int]? var completed: Bool! beforeEach { zippedValues = nil completed = false let (baseSignalA, baseObserverA) = Signal<Int, NoError>.pipe() let (baseSignalB, baseObserverB) = Signal<Int, NoError>.pipe() let (baseSignalC, baseObserverC) = Signal<Int, NoError>.pipe() signalA = baseSignalA signalB = baseSignalB signalC = baseSignalC observerA = baseObserverA observerB = baseObserverB observerC = baseObserverC } let zipExampleName = "zip examples" sharedExamples(zipExampleName) { it("should combine all set"){ expect(zippedValues).to(beNil()) observerA.send(value: 0) expect(zippedValues).to(beNil()) observerB.send(value: 1) expect(zippedValues).to(beNil()) observerC.send(value: 2) expect(zippedValues) == [0, 1, 2] observerA.send(value: 10) expect(zippedValues) == [0, 1, 2] observerA.send(value: 20) expect(zippedValues) == [0, 1, 2] observerB.send(value: 11) expect(zippedValues) == [0, 1, 2] observerC.send(value: 12) expect(zippedValues) == [10, 11, 12] } it("should complete when the shorter signal has completed"){ expect(completed) == false observerB.send(value: 1) observerC.send(value: 2) observerB.sendCompleted() observerC.sendCompleted() expect(completed) == false observerA.send(value: 0) expect(completed) == true } } describe("tuple") { beforeEach { Signal.zip(signalA, signalB, signalC) .observe { event in switch event { case let .value(value): zippedValues = [value.0, value.1, value.2] case .completed: completed = true default: break } } } itBehavesLike(zipExampleName) } describe("sequence") { beforeEach { Signal.zip([signalA, signalB, signalC]) .observe { event in switch event { case let .value(values): zippedValues = values case .completed: completed = true default: break } } } itBehavesLike(zipExampleName) } describe("log events") { it("should output the correct event without identifier") { let expectations: [(String) -> Void] = [ { event in expect(event) == "[] value 1" }, { event in expect(event) == "[] completed" }, { event in expect(event) == "[] terminated" }, { event in expect(event) == "[] disposed" }, ] let logger = TestLogger(expectations: expectations) let (signal, observer) = Signal<Int, NoError>.pipe() signal .logEvents(logger: logger.logEvent) .observe { _ in } observer.send(value: 1) observer.sendCompleted() } it("should output the correct event with identifier") { let expectations: [(String) -> Void] = [ { event in expect(event) == "[test.rac] value 1" }, { event in expect(event) == "[test.rac] failed error1" }, { event in expect(event) == "[test.rac] terminated" }, { event in expect(event) == "[test.rac] disposed" }, ] let logger = TestLogger(expectations: expectations) let (signal, observer) = Signal<Int, TestError>.pipe() signal .logEvents(identifier: "test.rac", logger: logger.logEvent) .observe { _ in } observer.send(value: 1) observer.send(error: .error1) } it("should only output the events specified in the `events` parameter") { let expectations: [(String) -> Void] = [ { event in expect(event) == "[test.rac] failed error1" }, ] let logger = TestLogger(expectations: expectations) let (signal, observer) = Signal<Int, TestError>.pipe() signal .logEvents(identifier: "test.rac", events: [.failed], logger: logger.logEvent) .observe { _ in } observer.send(value: 1) observer.send(error: .error1) } } } describe("negated attribute") { it("should return the negate of a value in a Boolean signal") { let (signal, observer) = Signal<Bool, NoError>.pipe() signal.negate().observeValues { value in expect(value).to(beFalse()) } observer.send(value: true) observer.sendCompleted() } } describe("and attribute") { it("should emit true when both signals emits the same value") { let (signal1, observer1) = Signal<Bool, NoError>.pipe() let (signal2, observer2) = Signal<Bool, NoError>.pipe() signal1.and(signal2).observeValues { value in expect(value).to(beTrue()) } observer1.send(value: true) observer2.send(value: true) observer1.sendCompleted() observer2.sendCompleted() } it("should emit false when both signals emits opposite values") { let (signal1, observer1) = Signal<Bool, NoError>.pipe() let (signal2, observer2) = Signal<Bool, NoError>.pipe() signal1.and(signal2).observeValues { value in expect(value).to(beFalse()) } observer1.send(value: false) observer2.send(value: true) observer1.sendCompleted() observer2.sendCompleted() } } describe("or attribute") { it("should emit true when at least one of the signals emits true") { let (signal1, observer1) = Signal<Bool, NoError>.pipe() let (signal2, observer2) = Signal<Bool, NoError>.pipe() signal1.or(signal2).observeValues { value in expect(value).to(beTrue()) } observer1.send(value: true) observer2.send(value: false) observer1.sendCompleted() observer2.sendCompleted() } it("should emit false when both signals emits false") { let (signal1, observer1) = Signal<Bool, NoError>.pipe() let (signal2, observer2) = Signal<Bool, NoError>.pipe() signal1.or(signal2).observeValues { value in expect(value).to(beFalse()) } observer1.send(value: false) observer2.send(value: false) observer1.sendCompleted() observer2.sendCompleted() } } } } private func operation<T>(value: T?) throws -> T { guard let value = value else { throw TestError.default } return value }
24.76423
111
0.623801
f848bac31a7c679c8fbbc9114a42cee234f722c4
541
import Flutter import UIKit public class SwiftFlutterXUpdatePlugin: NSObject, FlutterPlugin { public static func register(with registrar: FlutterPluginRegistrar) { let channel = FlutterMethodChannel(name: "com.xuexiang/flutter_xupdate", binaryMessenger: registrar.messenger()) let instance = SwiftFlutterXUpdatePlugin() registrar.addMethodCallDelegate(instance, channel: channel) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { result("iOS " + UIDevice.current.systemVersion) } }
36.066667
116
0.781885
c14fbdcec444e457e75cfcad62809344c82f9eef
2,135
// // AnyAppearanceType.swift // Designable IOS // // Created by incetro on 6/2/21. // import UIKit // MARK: - AnyAppearanceType /// Basic protocol for appearance type /// /// Generally, it will be a enum like this: /// /// // MARK: - AppearanceType /// /// enum AppearanceType: Int, AnyAppearanceType { /// /// case dark /// case light /// case graphite /// /// var name: String? { /// switch self { /// case .dark: /// return L10n.Themes.Types.dark /// case .light: /// return L10n.Themes.Types.light /// case .graphite: /// return L10n.Themes.Types.graphite /// } /// } /// /// var image: UIImage? { /// switch self { /// case .dark: /// return Asset.Settings.Appearance.darkAppearance.image /// case .light: /// return Asset.Settings.Appearance.lightAppearance.image /// case .graphite: /// return Asset.Settings.Appearance.graphiteAppearance.image /// } /// } /// } /// public protocol AnyAppearanceType: Codable { /// Your custom appearance name. /// This property added for cases when you have /// some UI component that should visualize all of your appearance types /// Default is nil var name: String? { get } /// Your custom appearance image. /// This property added for cases when you have /// some UI component that should visualize all of your appearance types /// Default is nil var image: UIImage? { get } } // MARK: - Default public extension AnyAppearanceType { /// Your custom appearance name. /// This property added for cases when you have /// some UI component that should visualize all of your appearance types var name: String? { nil } /// Your custom appearance image. /// This property added for cases when you have /// some UI component that should visualize all of your appearance types /// Default is nil var image: UIImage? { nil } }
27.727273
77
0.575176
f5a7b1f00b40b7c4d53f9831fdaf19a1af8fd193
1,195
/* Copyright 2019 Tua Rua Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import FreSwift import FacebookCore import FacebookShare public extension SharePhotoContent { convenience init?(_ freObject: FREObject?) { guard let rv = freObject else { return nil } self.init() let fre = FreObjectSwift(rv) if let contentUrl: String = fre.contentUrl, let url = URL(string: contentUrl) { contentURL = url } if let _hashtag: String = fre.hashtag { hashtag = Hashtag(_hashtag) } placeID = fre.placeId pageID = fre.pageId photos = fre.photos peopleIDs = fre.peopleIds } }
30.641026
87
0.68954
791b0e99caad309d5a46bf5c8f3ddcf9f1a56471
2,807
// // AppDelegate.swift // iOSSocialMediaApp // // Created by Henry Paulino on 10/20/18. // Copyright © 2018 Henry Paulino. All rights reserved. // import UIKit import Firebase import AppCenter import AppCenterAnalytics import AppCenterCrashes @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FirebaseApp.configure() MSAppCenter.start("c5126e70-a0fa-439e-af91-4621f2f0c5a0", withServices:[ MSAnalytics.self, MSCrashes.self ]) let settings = FirestoreSettings() Firestore.firestore().settings = settings Global.FS = Firestore.firestore() let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main) let mainViewController = mainStoryBoard.instantiateViewController(withIdentifier: "MainView") as! UITabBarController let user = Auth.auth().currentUser if user != nil { Global.currentUser = user! self.window!.rootViewController = mainViewController self.window!.makeKeyAndVisible() } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
41.895522
279
0.786605
873373f8a871114e5619b024888e8c6f5dfc76e7
551
// // Localization.swift // MunkiStatus // // Created by Greg Neagle on 27.05.18. // Copyright © 2018-2019 The Munki Project. All rights reserved. // import Cocoa // LaunchAgents run under "LimitLoadToSessionType : LoginWindow" on boot seem to be run // before a CGSession is setup. Wait until the session is available before handing // execution over to NSApplicationMain(). while CGSessionCopyCurrentDictionary() == nil { print("Waiting for a CGSession...") usleep(500000) } _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)
29
87
0.747731
4b0c363e819daf371d645b91b9dfa2ba69e0c608
2,183
// // AppDelegate.swift // VISPER-Swift-Task-Example // // Created by bartel on 25.12.17. // Copyright © 2017 Jan Bartel. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.446809
285
0.755383
8714c7c9448ed52f80c675738d33b28149110999
11,141
// // VerifyOtpViewController.swift // Dorothy // // Created by Adarsh Raj on 30/07/21. // import UIKit class VerifyOtpViewController: UIViewController { @IBOutlet weak var sectionView: UIView! @IBOutlet weak var mobileNumberLabel: UILabel! @IBOutlet weak var otpTextField1: UITextField! @IBOutlet weak var otpTextField2: UITextField! @IBOutlet weak var otpTextField3: UITextField! @IBOutlet weak var backView: UIView! @IBOutlet weak var otpTextField4: UITextField! @IBOutlet weak var verifyBtn: UIButton! @IBOutlet weak var otpTextFieldBottomLabel1: UILabel! @IBOutlet weak var otpTextFieldBottomLabel3: UILabel! @IBOutlet weak var otpTextFieldBottomLabel2: UILabel! @IBOutlet weak var otpTextFieldBottomLabel4: UILabel! var mobile:String = "" var country_code:String = "" var otp:String = "" var code:String = "" var isLoggedUser = 0 override func viewDidLoad() { super.viewDidLoad() setupThings() mobileLabelDisplay() } override func viewWillAppear(_ animated: Bool) { navigationController?.navigationBar.isHidden = true } @IBAction func resendCodeBtnAction(_ sender: Any) { if isLoggedUser == 1{ resendOTPToChangeMobileAPi() }else{ resendOTPAPi() } } @IBAction func verifyOtpBtnAction(_ sender: Any) { let otp1 = validateNumber(otpTextField1!.text!) let otp2 = validateNumber(otpTextField2!.text!) let otp3 = validateNumber(otpTextField3!.text!) let otp4 = validateNumber(otpTextField4!.text!) if otpTextField1!.text! == "" || otpTextField2!.text! == "" || otpTextField3!.text! == "" || otpTextField4!.text! == "" { Alert.showError(title: "Error", message: "Please enter OTP!!!", vc: self) }else if otp1 == false || otp2 == false || otp3 == false || otp4 == false { Alert.showError(title: "Error", message: "Invalid OTP!!!", vc: self) }else if isLoggedUser == 1{ code = "\(otpTextField1.text!)" + "\(otpTextField2.text!)" + "\(otpTextField3.text!)" + "\(otpTextField4.text!)" changeMobileVerifyOTPAPI() } else{ code = "\(otpTextField1.text!)" + "\(otpTextField2.text!)" + "\(otpTextField3.text!)" + "\(otpTextField4.text!)" verifyOTPAPI() } } @IBAction func backBtn(_ sender: UIButton) { backBtn() } @objc func textFieldDidChange(textField: UITextField){ let text = textField.text if (text?.utf16.count)! >= 1{ switch textField{ case otpTextField1: otpTextField2.becomeFirstResponder() case otpTextField2: otpTextField3.becomeFirstResponder() case otpTextField3: otpTextField4.becomeFirstResponder() case otpTextField4: otpTextField4.resignFirstResponder() default: break } }else{ } } func setupThings() { setGradientBackground(view: backView) sectionView.layer.cornerRadius = 60 sectionView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner] otpTextFieldBottomLabel1?.layer.cornerRadius = (otpTextFieldBottomLabel1?.frame.size.height)!/2.0 otpTextFieldBottomLabel1?.layer.masksToBounds = true otpTextFieldBottomLabel2?.layer.cornerRadius = (otpTextFieldBottomLabel2?.frame.size.height)!/2.0 otpTextFieldBottomLabel2?.layer.masksToBounds = true otpTextFieldBottomLabel3?.layer.cornerRadius = (otpTextFieldBottomLabel3?.frame.size.height)!/2.0 otpTextFieldBottomLabel3?.layer.masksToBounds = true otpTextFieldBottomLabel4?.layer.cornerRadius = (otpTextFieldBottomLabel4?.frame.size.height)!/2.0 otpTextFieldBottomLabel4?.layer.masksToBounds = true verifyBtn.layer.cornerRadius = 30 otpTextField1.layer.cornerRadius = 10 otpTextField2.layer.cornerRadius = 10 otpTextField3.layer.cornerRadius = 10 otpTextField4.layer.cornerRadius = 10 otpTextField1.delegate = self otpTextField2.delegate = self otpTextField3.delegate = self otpTextField4.delegate = self otpTextField1.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged) otpTextField2.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged) otpTextField3.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged) otpTextField4.addTarget(self, action: #selector(self.textFieldDidChange(textField:)), for: UIControl.Event.editingChanged) } func mobileLabelDisplay() { let mobileNumer = mobile let intLetters = mobileNumer.prefix(2) let endLetters = mobileNumer.suffix(2) let newString = intLetters + "******" + endLetters mobileNumberLabel.text! = String(newString) self.showToast(message: "OTP :- \(otp)", seconds: 2.0) } } extension VerifyOtpViewController:UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { textField.text = "" } } //MARK:- Verify OTP API Calling extension VerifyOtpViewController { func verifyOTPAPI() -> Void { ProgressHud.show() let success:successHandler = { response in ProgressHud.hide() let json = response as! [String : Any] if json["responseCode"] as! Int == 1 { let vc = self.storyboard?.instantiateViewController(withIdentifier: "RegistrationViewController") as! RegistrationViewController vc.mobile = self.mobile self.navigationController?.pushViewController(vc, animated: true) DispatchQueue.main.async { self.showToast(message: json["responseText"] as! String, seconds: 1.5) } }else{ let mess = json["responseText"] as! String Alert.showError(title: "Error", message: mess, vc: self) } } let failure:failureHandler = { [weak self] error, errorMessage in ProgressHud.hide() DispatchQueue.main.async { Alert.showError(title: "Error", message: errorMessage, vc: self!) } } //Calling API let parameters:EIDictonary = ["phone": mobile,"otp":code] SERVICE_CALL.sendRequest(parameters: parameters, httpMethod: "POST", methodType: RequestedUrlType.verifyOTP, successCall: success, failureCall: failure) } } //MARK:- API Calling for Change Mobile Varification extension VerifyOtpViewController { func changeMobileVerifyOTPAPI() -> Void { ProgressHud.show() let success:successHandler = { response in ProgressHud.hide() let json = response as! [String : Any] if json["responseCode"] as! Int == 1 { let vC = self.storyboard?.instantiateViewController(withIdentifier: "MyProfileViewController") as! MyProfileViewController self.navigationController?.pushViewController(vC, animated: true) DispatchQueue.main.async { self.showToast(message: json["responseText"] as! String, seconds: 2.0) } }else{ let mess = json["responseText"] as! String Alert.showError(title: "Error", message: mess, vc: self) print("code--------",self.code) } } let failure:failureHandler = { [weak self] error, errorMessage in ProgressHud.hide() DispatchQueue.main.async { Alert.showError(title: "Error", message: errorMessage, vc: self!) } } //Calling API let parameters:EIDictonary = ["customer_id":getStringValueFromLocal(key: "user_id") ?? "0","phone_no": mobile,"otp":code] SERVICE_CALL.sendRequest(parameters: parameters, httpMethod: "POST", methodType: RequestedUrlType.change_mobile_otp_verify, successCall: success, failureCall: failure) } } //MARK:- RESEND OTP API Calling for Change Mobile Varification extension VerifyOtpViewController { func resendOTPToChangeMobileAPi() -> Void { ProgressHud.show() let success:successHandler = { response in ProgressHud.hide() let json = response as! [String : Any] if json["responseCode"] as! Int == 1 { //let responseData = json["responseData"] as! [String: Any] //self.showToast(message: json["responseText"] as! String, seconds: 1.0) self.otp = json["responseData"] as! String DispatchQueue.main.async { self.mobileLabelDisplay() } }else{ let mess = json["responseText"] as! String Alert.showError(title: "Error", message: mess, vc: self) } } let failure:failureHandler = { [weak self] error, errorMessage in ProgressHud.hide() DispatchQueue.main.async { // showAlertWith(title: "Error", message: errorMessage, view: self!) //self!.showError(title: "Error", message: errorMessage) Alert.showError(title: "Error", message: errorMessage, vc: self!) } } //Calling API let parameters:EIDictonary = ["code": country_code,"customer_id":getStringValueFromLocal(key: "user_id") ?? "0","phone_no":mobile] SERVICE_CALL.sendRequest(parameters: parameters, httpMethod: "POST", methodType: RequestedUrlType.change_phoneno, successCall: success, failureCall: failure) } } //MARK:- Resend OTP extension VerifyOtpViewController { func resendOTPAPi() -> Void { ProgressHud.show() let success:successHandler = { response in ProgressHud.hide() let json = response as! [String : Any] if json["responseCode"] as! Int == 1 { //self.showToast(message: json["responseText"] as! String, seconds: 1.0) self.otp = json["responseData"] as! String DispatchQueue.main.async { self.mobileLabelDisplay() } }else{ let mess = json["responseText"] as! String Alert.showError(title: "Error", message: mess, vc: self) } } let failure:failureHandler = { [weak self] error, errorMessage in ProgressHud.hide() DispatchQueue.main.async { // showAlertWith(title: "Error", message: errorMessage, view: self!) //self!.showError(title: "Error", message: errorMessage) Alert.showError(title: "Error", message: errorMessage, vc: self!) } } //Calling API let parameters:EIDictonary = ["code": country_code,"mobile_no":mobile] SERVICE_CALL.sendRequest(parameters: parameters, httpMethod: "POST", methodType: RequestedUrlType.sendOTP, successCall: success, failureCall: failure) } }
35.93871
171
0.631721
acf9bb24b1713d11f19228dc492b848f22810b74
2,526
// // AppDelegate.swift // HelloWorld // // Created by fengyuxiang on 2019/8/27. // Copyright © 2019 fengyuxiang. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame :UIScreen.main.bounds) self.window?.rootViewController = ViewController() self.window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. print("resign active") } 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. print("enter background") } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. print("enterforeground") } 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. print("become active") } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. print("terminated") } }
44.315789
285
0.730008
727c71c5658045766c0d8e3dc23ae91efe6d4d50
1,134
// // Library.swift // IFTTT SDK // // Copyright © 2020 IFTTT. All rights reserved. // import Foundation enum LibraryAccess: CustomDebugStringConvertible { case denied, restricted, notDetermined, authorized var canBeAuthorized: Bool { switch self { case .denied, .restricted: return false default: return true } } var debugDescription: String { switch self { case .authorized: return "Authorized" case .denied: return "Denied" case .notDetermined: return "Not determined" case .restricted: return "Restricted" } } } protocol Library { /// Maps the access authorization status of this native library to the `LibraryAccess` generalized type var access: LibraryAccess { get } /// Checks current access to this native library. If it's `notDetermined` then it requests access immediately. /// /// - Parameter completion: This will be called immediately if `access != .notDetermined` else it will prompt the user for access. func requestAccess(_ completion: @escaping (LibraryAccess) -> Void) }
29.076923
134
0.665785
e82ab03df03fe3c39a33bdf0a97e91e2bcf11194
2,796
// // Changelog.swift // GitBuddyCore // // Created by Antoine van der Lee on 05/02/2020. // Copyright © 2020 WeTransfer. All rights reserved. // import Foundation import OctoKit typealias PullRequestID = Int typealias IssueID = Int /// Generalizes different types of changelogs with either single or multiple sections. protocol Changelog: CustomStringConvertible { /// The pull requests ID and related issues IDs that are merged with the related release of this /// changelog. It is used to post update comments on corresponding PRs and issues when a release /// is published. var itemIdentifiers: [PullRequestID: [IssueID]] { get } } /// Represents a changelog with a single section of changelog items. struct SingleSectionChangelog: Changelog { let description: String let itemIdentifiers: [PullRequestID: [IssueID]] init(items: [ChangelogItem]) { description = ChangelogBuilder(items: items).build() itemIdentifiers = items.reduce(into: [:]) { result, item in let pullRequestID: PullRequestID = item.closedBy.number if var pullRequestIssues = result[pullRequestID] { guard let issue = item.input as? ChangelogIssue else { return } pullRequestIssues.append(issue.number) result[pullRequestID] = pullRequestIssues } else if let issue = item.input as? ChangelogIssue { result[pullRequestID] = [issue.number] } else { result[pullRequestID] = [] } } } } /// Represents a changelog with at least two sections, one for closed issues, the other for /// merged pull requests. struct SectionedChangelog: Changelog { let description: String let itemIdentifiers: [PullRequestID: [IssueID]] init(issues: [Issue], pullRequests: [PullRequest]) { description = """ **Closed issues:** \(ChangelogBuilder(items: issues.map { ChangelogItem(input: $0, closedBy: $0) }).build()) **Merged pull requests:** \(ChangelogBuilder(items: pullRequests.map { ChangelogItem(input: $0, closedBy: $0) }).build()) """ itemIdentifiers = pullRequests.reduce(into: [:]) { result, item in result[item.number] = item.body?.resolvingIssues() } } } extension PullRequest: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(id) } public static func == (lhs: PullRequest, rhs: PullRequest) -> Bool { return lhs.id == rhs.id } } extension Issue: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(id) } public static func == (lhs: Issue, rhs: Issue) -> Bool { return lhs.id == rhs.id } }
30.725275
107
0.639127
e9d5302aadd5256df9a3fbe09533fc1289f34cb3
2,212
// // UserImage.swift // Flickr // // Created by Labuser on 2/26/16. // Copyright © 2016 TeamKickAss. All rights reserved. // import UIKit import Parse class UserImage: NSObject { /** * Other methods */ /** Method to post user media to Parse by uploading image file - parameter image: Image that the user wants upload to parse - parameter caption: Caption text input by the user - parameter completion: Block to be executed after save operation is complete */ class func postUserImage(image: UIImage?, withCaption caption: String?, withCompletion completion: PFBooleanResultBlock?) -> PFObject{ // Create Parse object PFObject let media = PFObject(className: "UserImage") // Add relevant fields to the object media["media"] = getPFFileFromImage(image) // PFFile column type media["author"] = PFUser.currentUser() // Pointer column type that points to PFUser media["caption"] = caption media["likesCount"] = 0 media["commentsCount"] = 0 // Save object (following function will save the object in Parse asynchronously) media.saveInBackgroundWithBlock { (success:Bool, error:NSError?) -> Void in if let completion = completion{ completion(success, error) } if let caption = caption{ if success{ UserComment.postUserComment(caption, image: media, withCompletion: nil) } } } return media } /** Method to post user media to Parse by uploading image file - parameter image: Image that the user wants to upload to parse - returns: PFFile for the the data in the image */ class func getPFFileFromImage(image: UIImage?) -> PFFile? { // check if image is not nil if let image = image { // get image data and check if that is not nil if let imageData = UIImagePNGRepresentation(image) { return PFFile(name: "image.png", data: imageData) } } return nil } }
31.6
138
0.592676
4a38381d2645fb7162af8d44a31d6719138c9800
18,960
// // File.swift // DTTableViewManager // // Created by Denys Telezhkin on 13.08.17. // Copyright © 2017 Denys Telezhkin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import DTModelStorage /// Base class for objects, that implement various datasource and delegate methods from `UITableView`. Even though this class is declared as `open`, subclassing it is discouraged. Please subsclass concrete subclass of this class, such as `DTTableViewDelegate`. open class DTTableViewDelegateWrapper : NSObject { weak var delegate: AnyObject? var tableView: UITableView? { return manager?.tableView } var viewFactory: TableViewFactory? { return manager?.viewFactory } var storage: Storage? { return manager?.storage } var configuration: TableViewConfiguration? { return manager?.configuration } weak var manager: DTTableViewManager? /// Creates base wrapper for datasource and delegate implementations public init(delegate: AnyObject?, tableViewManager: DTTableViewManager) { self.delegate = delegate manager = tableViewManager } /// Array of `UITableViewDataSource` reactions for `DTTableViewDataSource` /// - SeeAlso: `EventReaction`. final var unmappedReactions = [EventReaction]() { didSet { delegateWasReset() } } func delegateWasReset() { // Subclasses need to override this method, resetting `UITableView` delegate or datasource. // Resetting delegate is needed, because UITableView caches results of `respondsToSelector` call, and never calls it again until `setDelegate` method is called. // We force UITableView to flush that cache and query us again, because with new event we might have new delegate or datasource method to respond to. } func shouldDisplayHeaderView(forSection index: Int) -> Bool { guard let storage = storage, let configuration = configuration else { return false } if storage.numberOfItems(inSection: index) == 0 && !configuration.displayHeaderOnEmptySection { return false } return true } func shouldDisplayFooterView(forSection index: Int) -> Bool { guard let storage = storage, let configuration = configuration else { return false } if storage.numberOfItems(inSection: index) == 0 && !configuration.displayFooterOnEmptySection { return false } return true } /// Returns header model for section at `index`, or nil if it is not found. /// /// If `TableViewConfiguration` `displayHeaderOnEmptySection` is false, this method also returns nil. final func headerModel(forSection index: Int) -> Any? { if !shouldDisplayHeaderView(forSection: index) { return nil } return RuntimeHelper.recursivelyUnwrapAnyValue((storage as? SupplementaryStorage)?.headerModel(forSection: index) as Any) } /// Returns footer model for section at `index`, or nil if it is not found. /// /// If `TableViewConfiguration` `displayFooterOnEmptySection` is false, this method also returns nil. final func footerModel(forSection index: Int) -> Any? { if !shouldDisplayFooterView(forSection: index) { return nil } return RuntimeHelper.recursivelyUnwrapAnyValue((storage as? SupplementaryStorage)?.footerModel(forSection: index) as Any) } final private func appendMappedReaction<View:UIView>(type: View.Type, reaction: EventReaction, signature: EventMethodSignature) { let compatibleMappings = (viewFactory?.mappings ?? []).filter { (($0.viewClass as? UIView.Type)?.isSubclass(of: View.self) ?? false) } if compatibleMappings.count == 0 { manager?.anomalyHandler.reportAnomaly(.eventRegistrationForUnregisteredMapping(viewClass: String(describing: View.self), signature: signature.rawValue)) } compatibleMappings.forEach { mapping in mapping.reactions.append(reaction) } delegateWasReset() } final internal func appendReaction<Cell, ReturnType>(for cellClass: Cell.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (Cell, Cell.ModelType, IndexPath) -> ReturnType) where Cell: ModelTransfer, Cell:UITableViewCell { let reaction = EventReaction(viewType: Cell.self, modelType: Cell.ModelType.self, signature: signature.rawValue, closure) appendMappedReaction(type: Cell.self, reaction: reaction, signature: signature) manager?.verifyViewEvent(for: Cell.self, methodName: methodName) } final internal func append4ArgumentReaction<CellClass, Argument, Result> (for cellClass: CellClass.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (Argument, CellClass, CellClass.ModelType, IndexPath) -> Result) where CellClass: ModelTransfer, CellClass: UITableViewCell { let reaction = FourArgumentsEventReaction(CellClass.self, modelType: CellClass.ModelType.self, argument: Argument.self, signature: signature.rawValue, closure) appendMappedReaction(type: CellClass.self, reaction: reaction, signature: signature) manager?.verifyViewEvent(for: CellClass.self, methodName: methodName) } final internal func append5ArgumentReaction<CellClass, ArgumentOne, ArgumentTwo, Result> (for cellClass: CellClass.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (ArgumentOne, ArgumentTwo, CellClass, CellClass.ModelType, IndexPath) -> Result) where CellClass: ModelTransfer, CellClass: UITableViewCell { let reaction = FiveArgumentsEventReaction(CellClass.self, modelType: CellClass.ModelType.self, argumentOne: ArgumentOne.self, argumentTwo: ArgumentTwo.self, signature: signature.rawValue, closure) appendMappedReaction(type: CellClass.self, reaction: reaction, signature: signature) manager?.verifyViewEvent(for: CellClass.self, methodName: methodName) } final internal func appendReaction<Model, ReturnType>(viewType: ViewType, for modelClass: Model.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (Model, IndexPath) -> ReturnType) { let reaction = EventReaction(modelType: Model.self, signature: signature.rawValue, closure) appendMappedReaction(viewType: viewType, modelType: Model.self, reaction: reaction, signature: signature) manager?.verifyItemEvent(for: Model.self, eventMethod: methodName) } final func appendReaction<View, ReturnType>(forSupplementaryKind kind: String, supplementaryClass: View.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (View, View.ModelType, Int) -> ReturnType) where View: ModelTransfer, View: UIView { let reaction = EventReaction(viewType: View.self, modelType: View.ModelType.self, signature: signature.rawValue, { cell, model, indexPath in closure(cell, model, indexPath.section) }) appendMappedReaction(viewType: .supplementaryView(kind: kind), type: View.self, reaction: reaction, signature: signature) manager?.verifyViewEvent(for: View.self, methodName: methodName) } final private func appendMappedReaction<View:UIView>(viewType: ViewType, type: View.Type, reaction: EventReaction, signature: EventMethodSignature) { let compatibleMappings = (viewFactory?.mappings ?? []).filter { (($0.viewClass as? UIView.Type)?.isSubclass(of: View.self) ?? false) && $0.viewType == viewType } if compatibleMappings.count == 0 { manager?.anomalyHandler.reportAnomaly(.eventRegistrationForUnregisteredMapping(viewClass: String(describing: View.self), signature: signature.rawValue)) } compatibleMappings.forEach { mapping in mapping.reactions.append(reaction) } delegateWasReset() } final private func appendMappedReaction<Model>(viewType: ViewType, modelType: Model.Type, reaction: EventReaction, signature: EventMethodSignature) { let compatibleMappings = (viewFactory?.mappings ?? []).filter { $0.viewType == viewType && $0.modelTypeTypeCheckingBlock(Model.self) } if compatibleMappings.count == 0 { manager?.anomalyHandler.reportAnomaly(.eventRegistrationForUnregisteredMapping(viewClass: String(describing: Model.self), signature: signature.rawValue)) } compatibleMappings.forEach { mapping in mapping.reactions.append(reaction) } delegateWasReset() } final func appendReaction<Model, ReturnType>(forSupplementaryKind kind: String, modelClass: Model.Type, signature: EventMethodSignature, methodName: String = #function, closure: @escaping (Model, Int) -> ReturnType) { let reaction = EventReaction(modelType: Model.self, signature: signature.rawValue) { model, indexPath in closure(model, indexPath.section) } appendMappedReaction(viewType: .supplementaryView(kind: kind), modelType: Model.self, reaction: reaction, signature: signature) manager?.verifyItemEvent(for: Model.self, eventMethod: methodName) } final func appendNonCellReaction(_ signature: EventMethodSignature, closure: @escaping () -> Any) { unmappedReactions.append(EventReaction(signature: signature.rawValue, closure)) } final func appendNonCellReaction<Arg>(_ signature: EventMethodSignature, closure: @escaping (Arg) -> Any) { unmappedReactions.append(EventReaction(argument: Arg.self, signature: signature.rawValue, closure)) } final func appendNonCellReaction<Arg1, Arg2, Result>(_ signature: EventMethodSignature, closure: @escaping (Arg1, Arg2) -> Result) { unmappedReactions.append(EventReaction(argumentOne: Arg1.self, argumentTwo: Arg2.self, signature: signature.rawValue, closure)) } final func performCellReaction(_ signature: EventMethodSignature, location: IndexPath, provideCell: Bool) -> Any? { var cell : UITableViewCell? if provideCell { cell = tableView?.cellForRow(at: location) } guard let model = storage?.item(at: location) else { return nil } return EventReaction.performReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, view: cell, model: model, location: location) } final func perform4ArgumentCellReaction(_ signature: EventMethodSignature, argument: Any, location: IndexPath, provideCell: Bool) -> Any? { var cell : UITableViewCell? if provideCell { cell = tableView?.cellForRow(at: location) } guard let model = storage?.item(at: location) else { return nil } return EventReaction.perform4ArgumentsReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, argument: argument, view: cell, model: model, location: location) } final func perform5ArgumentCellReaction(_ signature: EventMethodSignature, argumentOne: Any, argumentTwo: Any, location: IndexPath, provideCell: Bool) -> Any? { var cell : UITableViewCell? if provideCell { cell = tableView?.cellForRow(at: location) } guard let model = storage?.item(at: location) else { return nil } return EventReaction.perform5ArgumentsReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, firstArgument: argumentOne, secondArgument: argumentTwo, view: cell, model: model, location: location) } final func performNillableCellReaction(_ reaction: EventReaction, location: IndexPath, provideCell: Bool) -> Any? { var cell : UITableViewCell? if provideCell { cell = tableView?.cellForRow(at: location) } guard let model = storage?.item(at: location) else { return nil } return reaction.performWithArguments((cell as Any, model, location)) } final func cellReaction(_ signature: EventMethodSignature, location: IndexPath) -> EventReaction? { guard let model = storage?.item(at: location) else { return nil } return EventReaction.reaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, forModel: model, at: location, view: nil) } final func performHeaderReaction(_ signature: EventMethodSignature, location: Int, provideView: Bool) -> Any? { var view : UIView? if provideView { view = tableView?.headerView(forSection: location) } guard let model = headerModel(forSection: location) else { return nil } return EventReaction.performReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, view: view, model: model, location: IndexPath(item: 0, section: location), supplementaryKind: DTTableViewElementSectionHeader) } final func performFooterReaction(_ signature: EventMethodSignature, location: Int, provideView: Bool) -> Any? { var view : UIView? if provideView { view = tableView?.footerView(forSection: location) } guard let model = footerModel(forSection: location) else { return nil } return EventReaction.performReaction(from: viewFactory?.mappings ?? [], signature: signature.rawValue, view: view, model: model, location: IndexPath(item: 0, section: location), supplementaryKind: DTTableViewElementSectionFooter) } func performNonCellReaction(_ signature: EventMethodSignature) -> Any? { EventReaction.performUnmappedReaction(from: unmappedReactions, signature.rawValue) } func performNonCellReaction<Argument>(_ signature: EventMethodSignature, argument: Argument) -> Any? { EventReaction.performUnmappedReaction(from: unmappedReactions, signature.rawValue, argument: argument) } func performNonCellReaction<ArgumentOne, ArgumentTwo>(_ signature: EventMethodSignature, argumentOne: ArgumentOne, argumentTwo: ArgumentTwo) -> Any? { EventReaction.performUnmappedReaction(from: unmappedReactions, signature.rawValue, argumentOne: argumentOne, argumentTwo: argumentTwo) } // MARK: - Target Forwarding /// Forwards `aSelector`, that is not implemented by `DTTableViewManager` to delegate, if it implements it. /// /// - Returns: `DTTableViewManager` delegate override open func forwardingTarget(for aSelector: Selector) -> Any? { return delegate } private func shouldEnableMethodCall(signature: EventMethodSignature) -> Bool { switch signature { case .heightForHeaderInSection: return configuration?.semanticHeaderHeight ?? false case .heightForFooterInSection: return configuration?.semanticFooterHeight ?? false default: return false } } /// Returns true, if `DTTableViewManageable` implements `aSelector`, or `DTTableViewManager` has an event, associated with this selector. /// /// - SeeAlso: `EventMethodSignature` override open func responds(to aSelector: Selector) -> Bool { if delegate?.responds(to: aSelector) ?? false { return true } if super.responds(to: aSelector) { if let eventSelector = EventMethodSignature(rawValue: String(describing: aSelector)) { return (unmappedReactions.contains { $0.methodSignature == eventSelector.rawValue } || (viewFactory?.mappings ?? []) .contains(where: { mapping in mapping.reactions.contains(where: { reaction in reaction.methodSignature == eventSelector.rawValue }) })) || shouldEnableMethodCall(signature: eventSelector) } return true } return false } }
54.326648
263
0.631382
2fe767be4257f4477b0cd90febcd3ed635cce1bc
767
// Copyright 2021 FlowAllocator LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import XCTest #if !canImport(ObjectiveC) public func allTests() -> [XCTestCaseEntry] { [ testCase(FINporterTests.allTests), ] } #endif
31.958333
75
0.711864
916d75bb73c7890a25ec32ef18f9bd0239f70683
228
// // Copyright © 2018 Avast. All rights reserved. // import Foundation public protocol TopeeLogger { func debug(_ msg: String) func info(_ msg: String) func warning(_ msg: String) func error(_ msg: String) }
17.538462
48
0.671053
204a671f8e20c92e93a3f780e0178e39b8f57751
1,245
// // NavigationController.swift // Copyright © 2018 wataru maeda. All rights reserved. // import UIKit class NavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() } func setupTheme(_ barTintColor: UIColor = .darkGray, barStyle: UIBarStyle = .black, tintColor: UIColor = .white, isTranslucent: Bool = false) { delegate = self // Navigation bar background color navigationBar.barTintColor = barTintColor // Change Button, label text color navigationBar.barStyle = barStyle navigationBar.tintColor = tintColor // Navigation controller title color navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white] navigationBar.isTranslucent = false } } // MARK: - UINavigationControllerDelegate extension NavigationController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { } } // MARK: - Supporting Functions extension NavigationController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
24.9
136
0.71004
3823bf042e69ac68f6fb0b15dc0793a67ffa30c5
892
// // ConversationChatEventTopicChatConversation.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation public class ConversationChatEventTopicChatConversation: Codable { public var _id: String? public var name: String? public var participants: [ConversationChatEventTopicChatMediaParticipant]? public var otherMediaUris: [String]? public init(_id: String?, name: String?, participants: [ConversationChatEventTopicChatMediaParticipant]?, otherMediaUris: [String]?) { self._id = _id self.name = name self.participants = participants self.otherMediaUris = otherMediaUris } public enum CodingKeys: String, CodingKey { case _id = "id" case name case participants case otherMediaUris } }
21.756098
138
0.665919
e062c454008e7b0aa7cac062a0d3da9c92a6e5ca
2,833
import XCTest import Apollo import ApolloTestSupport @testable import ApolloWebSocket class WebSocketTransportTests: XCTestCase { private var webSocketTransport: WebSocketTransport! override func tearDown() { webSocketTransport = nil super.tearDown() } func testUpdateHeaderValues() { var request = URLRequest(url: TestURL.mockServer.url) request.addValue("OldToken", forHTTPHeaderField: "Authorization") self.webSocketTransport = WebSocketTransport(websocket: MockWebSocket(request: request), store: ApolloStore()) self.webSocketTransport.updateHeaderValues(["Authorization": "UpdatedToken"]) XCTAssertEqual(self.webSocketTransport.websocket.request.allHTTPHeaderFields?["Authorization"], "UpdatedToken") } func testUpdateConnectingPayload() { let request = URLRequest(url: TestURL.mockServer.url) self.webSocketTransport = WebSocketTransport(websocket: MockWebSocket(request: request), store: ApolloStore(), connectingPayload: ["Authorization": "OldToken"]) let mockWebSocketDelegate = MockWebSocketDelegate() let mockWebSocket = self.webSocketTransport.websocket as? MockWebSocket self.webSocketTransport.socketConnectionState.mutate { $0 = .connected } mockWebSocket?.delegate = mockWebSocketDelegate let exp = expectation(description: "Waiting for reconnect") mockWebSocketDelegate.didReceiveMessage = { message in let json = try? JSONSerializationFormat.deserialize(data: message.data(using: .utf8)!) as? JSONObject guard let payload = json?["payload"] as? JSONObject, (json?["type"] as? String) == "connection_init" else { return } XCTAssertEqual(payload["Authorization"] as? String, "UpdatedToken") exp.fulfill() } self.webSocketTransport.updateConnectingPayload(["Authorization": "UpdatedToken"]) self.webSocketTransport.initServer() waitForExpectations(timeout: 3, handler: nil) } func testCloseConnectionAndInit() { let request = URLRequest(url: TestURL.mockServer.url) self.webSocketTransport = WebSocketTransport(websocket: MockWebSocket(request: request), store: ApolloStore(), connectingPayload: ["Authorization": "OldToken"]) self.webSocketTransport.closeConnection() self.webSocketTransport.updateConnectingPayload(["Authorization": "UpdatedToken"]) self.webSocketTransport.initServer() let exp = expectation(description: "Wait") let result = XCTWaiter.wait(for: [exp], timeout: 1.0) if result == XCTWaiter.Result.timedOut { } else { XCTFail("Delay interrupted") } } }
36.792208
115
0.680198
f8bcce0f0b52f2efba363a4133a4b1660c174fc8
1,117
import Foundation import Virtualization public func Configure(kernel:String, initrd:String, storage:[String], cmdline:String,processors:UInt64, memory:UInt64,network: Bool) -> VZVirtualMachineConfiguration { let configuration = VZVirtualMachineConfiguration() let entropy = VZVirtioEntropyDeviceConfiguration() let memoryBalloon = VZVirtioTraditionalMemoryBalloonDeviceConfiguration() configuration.cpuCount = Int(processors) configuration.memorySize = memory * 1024 * 1024 // memory(M) configuration.serialPorts = [ TerminalSerial() ] if !storage.isEmpty { configuration.storageDevices = StorageDevice(storage:storage) } if network { configuration.networkDevices = [NetworkDevice()] } configuration.bootLoader = BootLoader(kernel: kernel, initrd: initrd, cmdline:cmdline) configuration.entropyDevices = [ entropy ] configuration.memoryBalloonDevices = [ memoryBalloon ] do { try configuration.validate() } catch { print("configure lvm failed. \(error)") exit(EXIT_FAILURE) } return configuration }
38.517241
167
0.724261
e28de64556ebe082b9b0118709151d3453a89871
1,085
// // xWebImageView.swift // xWebImage // // Created by Mac on 2021/6/11. // import UIKit import xKit open class xWebImageView: xImageView { // MARK: - Public Property /// 图片链接 public var webImageURL = "" // MARK: - Open Override Func open override func viewDidLoad() { super.viewDidLoad() } // MARK: - Public Func /// 加载网络图片 public func xSetWebImage(url : String, placeholderImage : UIImage? = xWebImageManager.shared.placeholderImage, completed : (() -> Void)? = nil) { var str = url if url.hasPrefix("http") == false { str = xWebImageManager.shared.webImageURLPrefix + url } // 先解码再编码,防止URL已经编码导致2次编码 str = str.xToUrlDecodedString() ?? str str = str.xToUrlEncodedString() ?? str self.webImageURL = str self.sd_setImage(with: str.xToURL(), placeholderImage: placeholderImage, options: .retryFailed) { (img, err, _, _) in completed?() } } }
25.232558
105
0.55576
cca01b08d2df33cb5689be5102a20594d2e4dad2
3,900
// // ConfigurationSettings.swift // Alamofire // // Created by Lukasz Zajdel on 03/12/2018. // import Foundation //----------------------------------- public struct Product:Codable { let label:String let priceCents:Int public init(label:String,priceCents:Int){ self.label = label self.priceCents = priceCents } var dict:[String:Any]{ return [PledgUrlParametersName.productLabelParameter:label, PledgUrlParametersName.productPriceParameter:priceCents] } } public struct TransactionConfiguration{ let title:String let subtitle:String let merchantId:String let email:String let amountCents:Int let reference:String let currency:String let lang:String? let products:[Product]? public init(title:String,subtitle:String,merchantId:String,email:String,amountCents:Int,reference:String,currency:String, products:[Product]? = nil, lang:String? = nil ) { self.title = title self.subtitle = subtitle self.merchantId = merchantId self.email = email self.amountCents = amountCents self.reference = reference self.currency = currency self.lang = lang self.products = products } } extension TransactionConfiguration{ var url:URL{ var components = URLComponents() components.scheme = PledgSettings.baseURLScheme components.host = PledgSettings.baseURLString if let versionPath = PledgSettings.baseURLApiVersion, versionPath.isEmpty == false{ components.path = versionPath } var queryItems:[URLQueryItem] = [] queryItems.append(URLQueryItem(name: PledgUrlParametersName.embededParameter, value: "1")) queryItems.append(URLQueryItem(name: PledgUrlParametersName.sdkMobileParameter, value: "1")) if let languageCode = lang{ queryItems.append(URLQueryItem(name: PledgUrlParametersName.langParameter, value: languageCode)) }else if let languageCode = Locale.preferredLanguages.first{ queryItems.append(URLQueryItem(name: PledgUrlParametersName.langParameter, value: languageCode)) } queryItems.append(URLQueryItem(name: PledgUrlParametersName.titleParameter, value: title)) queryItems.append(URLQueryItem(name: PledgUrlParametersName.subtitleParameter, value: subtitle)) queryItems.append(URLQueryItem(name: PledgUrlParametersName.merchantIdParameter, value: merchantId)) queryItems.append(URLQueryItem(name: PledgUrlParametersName.emailParameter, value: email)) queryItems.append(URLQueryItem(name: PledgUrlParametersName.amountCentsParameter, value: "\(amountCents)")) queryItems.append(URLQueryItem(name: PledgUrlParametersName.referenceParameter, value: reference)) queryItems.append(URLQueryItem(name: PledgUrlParametersName.currencyParameter, value: currency)) if let products = products, products.isEmpty == false { let items = products.compactMap({ $0.dict}) do { let jsonData = try JSONSerialization.data(withJSONObject: items, options: []) if let decodedString = String(data: jsonData, encoding: .utf8){ queryItems.append(URLQueryItem(name: PledgUrlParametersName.productsParameter, value: decodedString )) } }catch let error{ print("JSON error:\(error)") } } components.queryItems = queryItems return components.url! } } //-----------------------------------
31.707317
176
0.622308
8ab6b688ce3cb9c26cd5783e1a97b6b3370a9ccd
935
import Foundation import Bow public final class ForFix {} public typealias FixPartial = ForFix public typealias FixOf<A> = Kind<ForFix, A> public class Fix<A>: FixOf<A> { public let unFix: Kind<A, Eval<FixOf<A>>> public static func fix(_ value: FixOf<A>) -> Fix<A> { value as! Fix<A> } public init(unFix: Kind<A, Eval<FixOf<A>>>) { self.unFix = unFix } } /// Safe downcast. /// /// - Parameter value: Value in higher-kind form. /// - Returns: Value cast to Fix. public postfix func ^<A>(_ value: FixOf<A>) -> Fix<A> { Fix.fix(value) } extension FixPartial: Recursive { public static func projectT<F: Functor>(_ tf: FixOf<F>) -> Kind<F, FixOf<F>> { F.map(tf^.unFix, { x in x.value() }) } } extension FixPartial: Corecursive { public static func embedT<F: Functor>(_ tf: Kind<F, Eval<FixOf<F>>>) -> Eval<FixOf<F>> { Eval.later { Fix(unFix: tf) } } }
23.974359
92
0.609626
f4e413969c5d521309bae1092cd04c4a699bf499
5,080
// // AlbumViewController.swift // SimplePlayer // // Created by Lihua Hu on 2014/07/03. // Copyright (c) 2014年 darkzero. All rights reserved. // import UIKit import MediaPlayer class AlbumViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { var albumsList:NSMutableArray; // init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { // super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // // Custom initialization // } required init(coder aDecoder: NSCoder) { self.albumsList = MusicLibrary.defaultPlayer().getiPodAlbumList(); super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // #pragma 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. } */ // MARK: - CollectionView dataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { NSLog("section count is %d", self.albumsList.count); return self.albumsList.count; } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { NSLog("row count is %d", self.albumsList[section].count); collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "ArtistCell"); return self.albumsList[section].count; } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath!) -> UICollectionReusableView { var sectionHeader:UICollectionReusableView = UICollectionReusableView(); if (kind == UICollectionElementKindSectionHeader) { sectionHeader = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "sectionHeader", forIndexPath: indexPath) as UICollectionReusableView; var collation:UILocalizedIndexedCollation = UILocalizedIndexedCollation.currentCollation() as UILocalizedIndexedCollation; //var sectionCount = (collation.sectionTitles as NSArray).count; var sectionTitle:NSString = collation.sectionTitles[indexPath.section] as NSString; (sectionHeader.subviews[0] as UILabel).text = sectionTitle; } return sectionHeader; } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { NSLog("now on row %d", indexPath.row); let cellIdentifier = "ArtistCell" var cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath:indexPath) as? UICollectionViewCell; if (cell == nil) { cell = UICollectionViewCell(); } cell!.backgroundColor = UIColor.whiteColor(); var mediaItemC: MPMediaItemCollection = ((self.albumsList[indexPath.section] as NSMutableArray)[indexPath.row]) as MPMediaItemCollection; var image = mediaItemC.representativeItem.artwork.imageWithSize(CGSize(width: 100, height: 100)); cell!.backgroundView = UIImageView(image: image); if ( cell!.viewWithTag(998) == nil ) { var artistLabel = UILabel(frame: CGRectMake(0, 80, 100, 20)); artistLabel.backgroundColor = UIColor(white: 0.6, alpha: 0.8); artistLabel.textColor = UIColor.blackColor(); artistLabel.font = UIFont.systemFontOfSize(12.0); artistLabel.tag = 998; artistLabel.textRectForBounds(CGRectMake(10, 80, 90, 20), limitedToNumberOfLines: 1) cell!.contentView.addSubview(artistLabel); } (cell!.viewWithTag(998) as UILabel).text = mediaItemC.representativeItem.albumTitle; return cell!; } // MARK: - CollectionView delegate func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) { collectionView.deselectItemAtIndexPath(indexPath, animated: false); var mediaItemC: MPMediaItemCollection = ((self.albumsList[indexPath.section] as NSMutableArray)[indexPath.row]) as MPMediaItemCollection; NSLog(mediaItemC.representativeItem.artist); // var alert:UIAlertView = UIAlertView(title: mediaItemC.representativeItem.artist, message: mediaItemC.representativeItem.albumTitle, delegate: nil, cancelButtonTitle: "Cancel"); // alert.show(); } }
43.418803
211
0.694094
7a1745e795de42d7d32f19eae620c19b087e37b2
29,064
// // ResponseSerialization.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// The type in which all data response serializers must conform to in order to serialize a response. public protocol DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, data and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<SerializedObject> { get } } // MARK: - /// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DataResponseSerializer<Value>: DataResponseSerializerProtocol { /// The type of serialized object to be created by this `DataResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, data and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value> /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) { self.serializeResponse = serializeResponse } } // MARK: - /// The type in which all download response serializers must conform to in order to serialize a response. public protocol DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializerType`. associatedtype SerializedObject /// A closure used by response handlers that takes a request, response, url and error and returns a result. var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<SerializedObject> { get } } // MARK: - /// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. public struct DownloadResponseSerializer<Value>: DownloadResponseSerializerProtocol { /// The type of serialized object to be created by this `DownloadResponseSerializer`. public typealias SerializedObject = Value /// A closure used by response handlers that takes a request, response, url and error and returns a result. public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value> /// Initializes the `ResponseSerializer` instance with the given serialize response closure. /// /// - parameter serializeResponse: The closure used to serialize the response. /// /// - returns: The new generic response serializer instance. public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>) { self.serializeResponse = serializeResponse } } // MARK: - Timeline extension Request { var timeline: Timeline { let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime return Timeline( requestStartTime: requestStartTime, initialResponseTime: initialResponseTime, requestCompletedTime: requestCompletedTime, serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) } } // MARK: - Default extension DataRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var dataResponse = DefaultDataResponse( request: self.request, response: self.response, data: self.delegate.data, error: self.delegate.error, timeline: self.timeline ) dataResponse.add(self.delegate.metrics) completionHandler(dataResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response<T: DataResponseSerializerProtocol>( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error ) var dataResponse = DataResponse<T.SerializedObject>( request: self.request, response: self.response, data: self.delegate.data, result: result, timeline: self.timeline ) dataResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } } return self } } extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response( queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDownloadResponse) -> Void) -> Self { delegate.queue.addOperation { (queue ?? DispatchQueue.main).async { var downloadResponse = DefaultDownloadResponse( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, error: self.downloadDelegate.error, timeline: self.timeline ) downloadResponse.add(self.delegate.metrics) completionHandler(downloadResponse) } } return self } /// Adds a handler to be called once the request has finished. /// /// - parameter queue: The queue on which the completion handler is dispatched. /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, /// and data contained in the destination url. /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func response<T: DownloadResponseSerializerProtocol>( queue: DispatchQueue? = nil, responseSerializer: T, completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void) -> Self { delegate.queue.addOperation { let result = responseSerializer.serializeResponse( self.request, self.response, self.downloadDelegate.fileURL, self.downloadDelegate.error ) var downloadResponse = DownloadResponse<T.SerializedObject>( request: self.request, response: self.response, temporaryURL: self.downloadDelegate.temporaryURL, destinationURL: self.downloadDelegate.destinationURL, resumeData: self.downloadDelegate.resumeData, result: result, timeline: self.timeline ) downloadResponse.add(self.delegate.metrics) (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } } return self } } // MARK: - Data extension Request { /// Returns a result data type that contains the response data as-is. /// /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } return .success(validData) } } extension DataRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DataResponseSerializer<Data> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseData(response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DataResponse<Data>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns the associated data as-is. /// /// - returns: A data response serializer. public static func dataResponseSerializer() -> DownloadResponseSerializer<Data> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseData(response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter completionHandler: The code to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DownloadResponse<Data>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.dataResponseSerializer(), completionHandler: completionHandler ) } } // MARK: - String extension Request { /// Returns a result string type initialized from the response data with the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseString( encoding: String.Encoding?, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<String> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } guard let validData = data else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) } var convertedEncoding = encoding if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil { convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName)) ) } let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1 if let string = String(data: validData, encoding: actualEncoding) { return .success(string) } else { return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) } } } extension DataRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DataResponse<String>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a result string type initialized from the response data with /// the specified string encoding. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server /// response, falling back to the default HTTP default character set, ISO-8859-1. /// /// - returns: A string response serializer. public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer<String> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the /// server response, falling back to the default HTTP default character set, /// ISO-8859-1. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseString( queue: DispatchQueue? = nil, encoding: String.Encoding? = nil, completionHandler: @escaping (DownloadResponse<String>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` /// with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponseJSON( options: JSONSerialization.ReadingOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Any> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let json = try JSONSerialization.jsonObject(with: validData, options: options) return .success(json) } catch { return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DataResponseSerializer<Any> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns a JSON object result type constructed from the response data using /// `JSONSerialization` with the specified reading options. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// /// - returns: A JSON object response serializer. public static func jsonResponseSerializer( options: JSONSerialization.ReadingOptions = .allowFragments) -> DownloadResponseSerializer<Any> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responseJSON( queue: DispatchQueue? = nil, options: JSONSerialization.ReadingOptions = .allowFragments, completionHandler: @escaping (DownloadResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), completionHandler: completionHandler ) } } // MARK: - Property List extension Request { /// Returns a plist object contained in a result type constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter response: The response from the server. /// - parameter data: The data returned from the server. /// - parameter error: The error already encountered if it exists. /// /// - returns: The result data type. public static func serializeResponsePropertyList( options: PropertyListSerialization.ReadOptions, response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Any> { guard error == nil else { return .failure(error!) } if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } guard let validData = data, validData.count > 0 else { return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) } do { let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) return .success(plist) } catch { return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) } } } extension DataRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DataResponseSerializer<Any> { return DataResponseSerializer { _, response, data, error in return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } extension DownloadRequest { /// Creates a response serializer that returns an object constructed from the response data using /// `PropertyListSerialization` with the specified reading options. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// /// - returns: A property list object response serializer. public static func propertyListResponseSerializer( options: PropertyListSerialization.ReadOptions = []) -> DownloadResponseSerializer<Any> { return DownloadResponseSerializer { _, response, fileURL, error in guard error == nil else { return .failure(error!) } guard let fileURL = fileURL else { return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) } do { let data = try Data(contentsOf: fileURL) return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) } catch { return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) } } } /// Adds a handler to be called once the request has finished. /// /// - parameter options: The property list reading options. Defaults to `[]`. /// - parameter completionHandler: A closure to be executed once the request has finished. /// /// - returns: The request. @discardableResult public func responsePropertyList( queue: DispatchQueue? = nil, options: PropertyListSerialization.ReadOptions = [], completionHandler: @escaping (DownloadResponse<Any>) -> Void) -> Self { return response( queue: queue, responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } } /// A set of HTTP response status code that do not contain response data. private let emptyDataStatusCodes: Set<Int> = [204, 205]
41.638968
126
0.651837
d7e6786a51564c31fc3556702abee566d6bbe8d3
4,785
// // File.swift // LogosUtils // // Created by Tom-Roger Mittag on 6/9/20. // Copyright © Tom-Roger Mittag. All rights reserved. // import Foundation public extension NSRegularExpression { static var allDigits = NSRegularExpression(#"^\d+$"#) static var allWhitespace = NSRegularExpression(#"^\s+$"#) static var allWhitespaceOrEmpty = NSRegularExpression(#"^\s*$"#) typealias DividedResults = (matching: String, notMatching: String) convenience init(_ pattern: String) { do { try self.init(pattern: pattern) } catch { preconditionFailure("Illegal regular expression: \(pattern).") } } func divide(string: String) -> DividedResults { let nsString = NSString(string: string) let fullRange = NSRange(location: 0, length: string.utf16.count) var previousMatchRange = NSRange(location: 0, length: 0) var divided: DividedResults = ("", "") for match in matches(in: string, range: fullRange) { // Extract the piece before the match let precedingRange = NSRange(location: previousMatchRange.upperBound, length: match.range.lowerBound - previousMatchRange.upperBound) divided.notMatching.append(nsString.substring(with: precedingRange)) // Extract the match let range = match.range(at: 0) if range.location != NSNotFound { divided.matching += nsString.substring(with: range) } previousMatchRange = match.range } // Extract the final piece let endingRange = NSRange(location: previousMatchRange.upperBound, length: fullRange.upperBound - previousMatchRange.upperBound) divided.notMatching.append(nsString.substring(with: endingRange)) return divided } func matches(string: String) -> Bool { let range = NSRange(location: 0, length: string.utf16.count) return firstMatch(in: string, options: [], range: range) != nil } func matchesToArray(string: String) -> [[String]] { let nsString = string as NSString let results = matches(in: string, options: [], range: NSMakeRange(0, nsString.length)) return results.map { result in (1 ..< result.numberOfRanges).map { result.range(at: $0).location != NSNotFound ? nsString.substring(with: result.range(at: $0)) : "" } } } func filter(string: String) -> String { let nsString = NSString(string: string) let fullRange = NSRange(location: 0, length: string.utf16.count) var result = "" for match in matches(in: string, range: fullRange) { let range = match.range(at: 0) if range.location != NSNotFound { result += nsString.substring(with: range) } } return result } func firstMatch(in string: String, options: MatchingOptions = [], range: Range<String.Index>? = nil) -> NSTextCheckingResult? { let nsRange = NSRange(range ?? string.startIndex ..< string.endIndex, in: string) return firstMatch(in: string, options: options, range: nsRange) } func replace(string: String, withTemplate: String) -> String { let range = NSRange(location: 0, length: string.count) return stringByReplacingMatches(in: string, options: [], range: range, withTemplate: withTemplate) } func split(string: String) -> [String] { var result = [String]() let nsString = NSString(string: string) let fullRange = NSRange(location: 0, length: string.utf16.count) var previousRange = NSRange(location: 0, length: 0) for match in matches(in: string, range: fullRange) { // Extract the piece before the match let precedingRange = NSRange(location: previousRange.upperBound, length: match.range.lowerBound - previousRange.upperBound) result.append(nsString.substring(with: precedingRange)) // Extract the groups for i in 1 ..< match.numberOfRanges { let range = match.range(at: i) if range.location != NSNotFound { result.append(nsString.substring(with: range)) } } previousRange = match.range } // Extract the final piece let endingRange = NSRange(location: previousRange.upperBound, length: fullRange.upperBound - previousRange.upperBound) result.append(nsString.substring(with: endingRange)) return result.filterOut(\.isBlank) } }
40.210084
145
0.602926
64d5de838180a504c2e07305f9ba5898d8e7c3e0
86
@testable import MistKit import XCTest final class MKTokenEncoderTests: XCTestCase {}
21.5
46
0.837209
de467ad4bb6a3006bb05119fe66d34a23465f6d8
1,094
/*: ## Exercise - Numeric Type Conversion Create an integer constant `x` with a value of 10, and a double constant `y` with a value of 3.2. Create a constant `multipliedAsIntegers` equal to `x` times `y`. Does this compile? If not, fix it by converting your `Double` to an `Int` in the mathematical expression. Print the result. */ let x = 10 let y = 3.2 let multipliedAsIntegers = x * Int(y) print(multipliedAsIntegers) /*: Create a constant `multipliedAsDoubles` equal to `x` times `y`, but this time convert the `Int` to a `Double` in the expression. Print the result. */ let multipliedAsDoubles = Double(x) * y print(multipliedAsDoubles) /*: Are the values of `multipliedAsIntegers` and `multipliedAsDoubles` different? Print a statement to the console explaining why. */ print("In multipliedAsIntegers the Double is rounded down to the Int 3 and hence the result is 30.") print("In multipliedAsDouble, the Int is converted to a Double and hence the calculation outputs 32 as expected.") //: [Previous](@previous) | page 7 of 8 | [Next: App Exercise - Converting Types](@next)
49.727273
287
0.73766
1a9e9f98d64ba4363a85807dd22372ddf6f4e8b1
1,643
// // sawtooth.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation extension AKOperation { /// Simple sawtooth oscillator, not-band limited, can be used for LFO or wave, /// but sawtoothWave is probably better for audio. /// /// - Parameters: /// - frequency: In cycles per second, or Hz. (Default: 440, Minimum: 0.0, Maximum: 20000.0) /// - amplitude: Output Amplitude. (Default: 0.5, Minimum: 0.0, Maximum: 1.0) /// public static func sawtooth( frequency frequency: AKParameter = 440, amplitude: AKParameter = 0.5, phase: AKParameter = 0 ) -> AKOperation { return AKOperation(module: "\"sawtooth\" osc", setup: "\"sawtooth\" 4096 \"0 -1 4095 1\" gen_line", inputs: frequency, amplitude, phase) } /// Simple reverse sawtooth oscillator, not-band limited, can be used for LFO or wave. /// /// - Parameters: /// - frequency: In cycles per second, or Hz. (Default: 440, Minimum: 0.0, Maximum: 20000.0) /// - amplitude: Output Amplitude. (Default: 0.5, Minimum: 0.0, Maximum: 1.0) /// public static func reverseSawtooth( frequency frequency: AKParameter = 440, amplitude: AKParameter = 0.5, phase: AKParameter = 0 ) -> AKOperation { return AKOperation(module: "\"revsaw\" osc", setup: "\"revsaw\" 4096 \"0 1 4095 -1\" gen_line", inputs: frequency, amplitude, phase) } }
34.957447
98
0.583688
f85456520fe1faa350494f37ece5caa9b91123d8
803
// // UserDAOTest.swift // TwitterMockTests // // Created by Tracy Wu on 2019-04-05. // Copyright © 2019 TW. All rights reserved. // import XCTest import RealmSwift @testable import TwitterMock class UserDAOTest: XCTestCase { var dao: RealmDAO<UserRM>! override func setUp() { super.setUp() dao = RealmDAO<UserRM>(inMemoryIdentifier: String(describing: self)) } override func tearDown() { dao.reset() super.tearDown() } func testSaveAndLoad() { XCTAssertEqual(dao.count, 0) let userRM = UserRM() userRM.id = 100 dao.save(model: userRM) XCTAssertEqual(dao.count, 1) let first = dao.first()! XCTAssertEqual(first.id, 100) } }
19.119048
76
0.574097
16d7318aa7eba784e1dd7497549648c86dd5a304
8,857
import UIKit import Alamofire import SwiftyJSON import Toast_Swift class LoginViewController: UIViewController { private let lbTitle: UILabel = { let lb = UILabel() lb.text = "登录" lb.textColor = .white lb.font = UIFont.systemFont(ofSize: 42, weight: .bold) return lb }() private let lbSubtitle: UILabel = { let lb = UILabel() lb.text = "Welcome back" lb.textColor = .white lb.font = UIFont.systemFont(ofSize: 36) return lb }() private let lbPhone: UILabel = { let lb = UILabel() lb.text = "手机号" lb.textColor = .darkGray lb.font = UIFont.systemFont(ofSize: 17) return lb }() private let txtPhone: UITextField = { let txt = UITextField() txt.placeholder = "请输入手机号" txt.keyboardType = .phonePad return txt }() private let lbPwd: UILabel = { let lb = UILabel() lb.text = "密码" return lb }() private let txtPwd: UITextField = { let txt = UITextField() txt.placeholder = "请输入密码" txt.isSecureTextEntry = true return txt }() private let btnLogin: UIButton = { let btn = UIButton() btn.setTitle("登 录", for: .normal) btn.backgroundColor = UIColor(hexString: "#FF6767") btn.titleLabel?.font = UIFont.systemFont(ofSize: 24, weight: .bold) btn.setCornerRadius(20) return btn }() private let btnToRegist: UIButton = { let btn = UIButton() var attributedString = NSMutableAttributedString(string: "没有账号?前往注册") var range = NSRange() range.location = 7 range.length = 2 attributedString.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.gray], range: NSRange(location: 0, length: 7)) attributedString.addAttributes([NSAttributedString.Key.link : "account://"], range: range) btn.setAttributedTitle(attributedString, for: .normal) return btn }() override var preferredStatusBarStyle: UIStatusBarStyle { return .default } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let bg = UIImageView() bg.frame = view.frame bg.image = UIImage(named: "yky_bg") bg.contentMode = .scaleAspectFit view.addSubview(bg) view.addSubview(lbTitle) view.addSubview(lbSubtitle) view.addSubview(lbPhone) view.addSubview(txtPhone) view.addSubview(lbPwd) view.addSubview(txtPwd) view.addSubview(btnLogin) view.addSubview(btnToRegist) lbTitle.anchor(top: view.guide.topAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 70, paddingLeft: 40, paddingBottom: 0, paddingRight: 0, width: Util.screenWidth-80, height: 44) lbSubtitle.anchor(top: lbTitle.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 40, paddingBottom: 0, paddingRight: 0, width: Util.screenWidth-80, height: 44) lbPhone.anchor(top: lbSubtitle.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 100, paddingLeft: 40, paddingBottom: 0, paddingRight: 0, width: Util.screenWidth-80, height: 20) txtPhone.anchor(top: lbPhone.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 10, paddingLeft: 40, paddingBottom: 0, paddingRight: 0, width: Util.screenWidth-80, height: 24) lbPwd.anchor(top: txtPhone.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 30, paddingLeft: 40, paddingBottom: 0, paddingRight: 0, width: Util.screenWidth-80, height: 20) txtPwd.anchor(top: lbPwd.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 10, paddingLeft: 40, paddingBottom: 0, paddingRight: 0, width: Util.screenWidth-80, height: 24) btnLogin.anchor(top: txtPwd.bottomAnchor, left: view.leftAnchor, bottom: nil, right: nil, paddingTop: 40, paddingLeft: 40, paddingBottom: 0, paddingRight: 0, width: Util.screenWidth-80, height: 40) btnToRegist.anchor(top: btnLogin.bottomAnchor, left: nil, bottom: nil, right: nil, paddingTop: 10, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 200, height: 20) btnToRegist.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard(tapG:))) tap.cancelsTouchesInView = false self.view.addGestureRecognizer(tap) btnLogin.addTarget(self, action: #selector(onTapLogin), for: .touchUpInside) btnToRegist.addTarget(self, action: #selector(onTapToRegist), for: .touchUpInside) setKefuUI() let vLogin = UIView(frame: CGRect(x: Util.screenWidth-64, y: 0, width: 64, height: 64)) // vLogin.borderWith = 1 // vLogin.borderColor = .red let doubleTap = UITapGestureRecognizer(target: self, action: #selector(onDoubleTap(tap:))) doubleTap.numberOfTapsRequired = 2 vLogin.addGestureRecognizer(doubleTap) view.addSubview(vLogin) } @objc private func onDoubleTap(tap:UITapGestureRecognizer) { doLogin(phone: "15821162092", pwd: "qqqqqq") } private func setKefuUI() { let btnKefu = createKefuBtn(img: "yky_kefu", title: "咨询客服") let btnDianhua = createKefuBtn(img: "yky_phone", title: "拨打电话") view.addSubview(btnKefu) view.addSubview(btnDianhua) let btn_weith = (Util.screenWidth - 60) / 2 btnKefu.anchor(top: nil, left: view.leftAnchor, bottom: view.guide.bottomAnchor, right: nil, paddingTop: 0, paddingLeft: 15, paddingBottom: 15, paddingRight: 0, width: btn_weith, height: 55) btnDianhua.anchor(top: nil, left: nil, bottom: view.guide.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 15, paddingRight: 15, width: btn_weith, height: 55) btnKefu.addTarget(self, action: #selector(onTapKefu), for: .touchUpInside) btnDianhua.addTarget(self, action: #selector(onTapDianhua), for: .touchUpInside) } @objc private func onTapKefu() { } @objc private func onTapDianhua() { onTapPhoneCall() } override func viewDidLayoutSubviews() { addBottomBorder(txtPhone) addBottomBorder(txtPwd) } private func addBottomBorder(_ txt: UITextField) { let btmBorder = CALayer() btmBorder.backgroundColor = UIColor.gray.cgColor btmBorder.frame = CGRect(x: 0, y: txt.frame.size.height-1, width: txt.frame.size.width, height: 1) txt.layer.addSublayer(btmBorder) } @objc func hideKeyboard(tapG: UITapGestureRecognizer) { self.view.endEditing(true) } @objc func onTapLogin() { guard let phone = txtPhone.text, phone.isPhone() else { view.makeToast("请输入有效的手机号码") return } guard let pwd = txtPwd.text, pwd.count > 5 && pwd.count < 21 else { view.makeToast("密码长度为6至20之间") return } doLogin(phone: phone, pwd: pwd) } private func doLogin(phone: String, pwd: String) { let parameters = ["username": phone, "password": pwd] Alamofire.request(adLogin, method: .post, parameters: parameters).responseJSON { [self] response in Log.debug(response) if let data = response.data { let json = JSON(data) if json["code"].int == 0 { view.makeToast("登录成功") UserDefaults.localData.keyAccount.store(value: phone) if let uid = json["data"]["uid"].int, let token = json["data"]["token"].string { rAdInit(uid: uid, phoneNum: phone, token: token) } rAdBaseInfo() self.dismiss(animated: false, completion: nil) NotificationCenter.default.post(name: NSNotification.Name(NotiName.openAd.rawValue), object: nil) } else { view.makeToast(json["msg"].string ?? "请求数据异常...") } } else { view.makeToast("请求失败,请稍候重试...") } } } @objc private func onTapToRegist() { self.dismiss(animated: false, completion: nil) NotificationCenter.default.post(name: NSNotification.Name(NotiName.openRegistView.rawValue), object: nil) } }
39.190265
209
0.609913
f5a4d2b1d3677d387e40f3c3a4a7622c42184925
1,351
// // AppDelegate.swift // Datify-iOS // // Created by Sobhan Asim on 06/10/2021. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
36.513514
179
0.745374
142a11d9b37cd01d971d5df6073c5a5a51504a99
48
import CurrencyKit extension CurrencyValue { }
9.6
25
0.8125
b9742534b884da7f218a5e1af8172fcb9cb12e93
4,637
// RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=GLOBAL_1 > %t // RUN: %FileCheck %s -check-prefix=GLOBAL_1 < %t // RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=METHOD_1 > %t // RUN: %FileCheck %s -check-prefix=METHOD_1 < %t // RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=METHOD_2 > %t // RUN: %FileCheck %s -check-prefix=GLOBAL_1 < %t // RUN: %FileCheck %s -check-prefix=METHOD_1 < %t // RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=METHOD_3 > %t // RUN: %FileCheck %s -check-prefix=METHOD_1 < %t // RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=STATIC_METHOD_1 > %t // RUN: %FileCheck %s -check-prefix=STATIC_METHOD_1 < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=METHOD_4 > %t // RUN: %FileCheck %s -check-prefix=METHOD_4 < %t // RUN: %FileCheck %s -check-prefix=NONTRIVIAL < %t // RUN: %target-swift-ide-test -code-completion -source-filename=%s -code-completion-token=CLASS_METHOD_1 > %t // RUN: %FileCheck %s -check-prefix=CLASS_METHOD_1 < %t // NONTRIVIAL-NOT: nonTrivial{{.*}} {|} func global1(_: ()->()) {} func global2(label: ()->()) {} func global3(_: () throws -> ()) rethrows {} func global4(x: Int = 0, y: Int = 2, _: ()->()) {} func nonTrivial1(_: (Int) -> ()) {} func nonTrivial2(_: () -> Int) {} func nonTrivial3(x: Int, _: () -> Int) {} func test1() { #^GLOBAL_1^# } // GLOBAL_1: Begin completions // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global1 {|}[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global2 {|}[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global3 {|}[' rethrows'][#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global4 {|}[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global1({#() -> ()##() -> ()#})[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global2({#label: () -> ()##() -> ()#})[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global3({#() throws -> ()##() throws -> ()#})[' rethrows'][#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global4({#() -> ()##() -> ()#})[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: global4({#x: Int#}, {#y: Int#}, {#() -> ()##() -> ()#})[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: nonTrivial1({#(Int) -> ()##(Int) -> ()#})[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: nonTrivial2({#() -> Int##() -> Int#})[#Void#] // GLOBAL_1-DAG: Decl[FreeFunction]/CurrModule: nonTrivial3({#x: Int#}, {#() -> Int##() -> Int#})[#Void#] // GLOBAL_1: End completions struct S { func method1(_: ()->()) {} static func method2(_: ()->()) {} static func method3(_ a: Int = 0, _: ()->()) {} func nonTrivial1(_: (Int)->()) {} func nonTrivial2(_: @autoclosure ()->()) {} func test2() { self.#^METHOD_1^# } // METHOD_1: Begin completions // METHOD_1: Decl[InstanceMethod]/CurrNominal: method1 {|}[#Void#] // METHOD_1: Decl[InstanceMethod]/CurrNominal: method1({#() -> ()##() -> ()#})[#Void#] // METHOD_1: Decl[InstanceMethod]/CurrNominal: nonTrivial1({#(Int) -> ()##(Int) -> ()#})[#Void#] // METHOD_1: Decl[InstanceMethod]/CurrNominal: nonTrivial2({#()#})[#Void#] // METHOD_1: End completions func test3() { #^METHOD_2^# } } func test4() { S().#^METHOD_3^# } func test5() { S.#^STATIC_METHOD_1^# } // STATIC_METHOD_1-NOT: {|} // STATIC_METHOD_1: Decl[StaticMethod]/CurrNominal: method2 {|}[#Void#] // STATIC_METHOD_1: Decl[StaticMethod]/CurrNominal: method3 {|}[#Void#] // STATIC_METHOD_1-NOT: {|} class C { func method1(_: ()->()) {} class func method2(_: ()->()) {} func nonTrivial1(_: (Int)->()) {} func nonTrivial2(_: @autoclosure ()->()) {} func test6() { self.#^METHOD_4^# } // METHOD_4: Begin completions // METHOD_4: Decl[InstanceMethod]/CurrNominal: method1 {|}[#Void#] // METHOD_4: Decl[InstanceMethod]/CurrNominal: method1({#() -> ()##() -> ()#})[#Void#] // METHOD_4: Decl[InstanceMethod]/CurrNominal: nonTrivial1({#(Int) -> ()##(Int) -> ()#})[#Void#] // METHOD_4: End completions func test7() { C.#^CLASS_METHOD_1^# } // CLASS_METHOD_1-NOT: {|} // CLASS_METHOD_1: Decl[StaticMethod]/CurrNominal: method2 {|}[#Void#] // CLASS_METHOD_1-NOT: {|} }
42.541284
119
0.620876
d57517c8dffd9b1e1aec8ae612005112ac9342df
166
// // CreditCardStyle.swift // FinancialApp // // Created by Craig Clayton on 6/28/20. // Copyright © 2020 Cocoa Academy. All rights reserved. // import SwiftUI
16.6
56
0.692771
ebfd5b89e59a12605ec11f434531c8ec1b17202d
1,043
// swift-tools-version:4.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "LooseCodable", products: [ // Products define the executables and libraries produced by a package, and make them visible to other packages. .library( name: "LooseCodable", targets: ["LooseCodable"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "LooseCodable", dependencies: []), .testTarget( name: "LooseCodableTests", dependencies: ["LooseCodable"]), ] )
35.965517
122
0.627037
e599a18b491de96d531e8716b89bd86122de79b6
2,008
// // UIView+LoadingExtension // VariousCurrentSituations // // Created by iganin on 2018/07/19. // Copyright © 2018年 iganin. All rights reserved. // import UIKit ///表示用のIndicator本体 UIViewのExtension以外からの生成を防ぐためfileprivateにしています fileprivate final class LoadingOverLayView: UIView { // MARK: - Property private var indicatorView: UIActivityIndicatorView! // MARK: - LifeCycle init(frame: CGRect, indicatorStyle: UIActivityIndicatorViewStyle) { indicatorView = UIActivityIndicatorView(activityIndicatorStyle: indicatorStyle) indicatorView.hidesWhenStopped = true super.init(frame: frame) addSubview(indicatorView) indicatorView.center = center backgroundColor = UIColor.black alpha = 0.4 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Method func startAnimation() { indicatorView.startAnimating() } func stopAnimation() { indicatorView.stopAnimating() } } // MARK: - UIView Extension extension UIView { /// LoadingViewを表示します /// /// - Parameter indicatorStyle: UIActivityIndicatorViewのstyle(gray, white, whiteLarge) func showLoading(with indicatorStyle: UIActivityIndicatorViewStyle = .whiteLarge) { // Loading中にはView操作をして欲しくないためユーザー操作を不可にしています isUserInteractionEnabled = false let overLayView = LoadingOverLayView(frame: frame, indicatorStyle: indicatorStyle) addSubview(overLayView) overLayView.edges(to: self) overLayView.startAnimation() } /// 表示されているIndicatorViewを非表示にします func hideLoading() { // Loadingを非表示にしたタイミングでユーザー操作を可能にしています isUserInteractionEnabled = true subviews.forEach { subView in if let subView = subView as? LoadingOverLayView { subView.stopAnimation() subView.removeFromSuperview() } } } }
29.101449
90
0.669323
769c6e89f701506ddb5e272014296f54a06c3a27
418
// // Bundle+Version.swift // CriticalMaps // // Created by Malte Bünz on 28.03.19. // Copyright © 2019 Pokus Labs. All rights reserved. // import Foundation import UIKit extension Bundle { var versionNumber: String { return infoDictionary?["CFBundleShortVersionString"] as? String ?? "" } var buildNumber: String { return infoDictionary?["CFBundleVersion"] as? String ?? "" } }
19.904762
77
0.660287
61990c87c433e7b27988d455d1d131e29a9b2490
1,156
// // ModelData.swift // Landmarks // // Created by Mehrdad Ahmanian on 2021-07-20. // import Foundation import Combine final class ModelData: ObservableObject { @Published var landmarks: [Landmark] = load("landmarkData.json") var hikes: [Hike] = load("hikeData.json") @Published var profile = Profile.default var features: [Landmark] { landmarks.filter { $0.isFeatured} } var categories: [String: [Landmark]] { Dictionary( grouping: landmarks, by: { $0.category.rawValue } ) } } func load<T: Decodable>(_ filename: String) -> T { let data: Data guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else { fatalError("Couldn't find \(filename) in main bundle.") } do { data = try Data(contentsOf: file) } catch { fatalError("Couldn't load \(filename) from main bundle: \n\(error)") } do { let decoder = JSONDecoder() return try decoder.decode(T.self, from: data) } catch { fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)") } }
24.083333
86
0.593426
0a5de735f3fe172584ae2dddbc73495730d88f30
278
@testable import SwiftyVK import XCTest final class SharePresenterMock: SharePresenter { var onShare: ((ShareContext) throws -> Data)? func share(_ context: ShareContext, in session: Session) throws -> Data { return try onShare?(context) ?? Data() } }
25.272727
77
0.683453
6154a4e8ff512c919ec274f0b44b99cceba86ba1
3,091
// // NetworkEventProducer_Tests.swift // AudioPlayer // // Created by Kevin DELANNOY on 08/03/16. // Copyright © 2016 Kevin Delannoy. All rights reserved. // import XCTest @testable import AudioPlayer class NetworkEventProducer_Tests: XCTestCase { var listener: FakeEventListener! var producer: NetworkEventProducer! var reachability: FakeReachability! override func setUp() { super.setUp() listener = FakeEventListener() reachability = try? FakeReachability() producer = NetworkEventProducer(reachability: reachability) producer.eventListener = listener producer.startProducingEvents() } override func tearDown() { listener = nil reachability = nil producer.stopProducingEvents() producer = nil super.tearDown() } func testEventListenerGetsCalledWhenChangingReachabilityStatus() { let e = expectation(description: "Waiting for `onEvent` to get called") listener.eventClosure = { event, producer in XCTAssertEqual(event as? NetworkEventProducer.NetworkEvent, NetworkEventProducer.NetworkEvent.connectionRetrieved) e.fulfill() } reachability.newConnection = .wifi waitForExpectations(timeout: 1) { e in if let _ = e { XCTFail() } } } func testEventListenerDoesNotGetCalledWhenReachabilityStatusDoesNotChange() { listener.eventClosure = { event, producer in XCTFail() } reachability.newConnection = reachability.connection let e = expectation(description: "Waiting for `onEvent` to get called") DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(200)) { e.fulfill() } waitForExpectations(timeout: 1) { e in if let _ = e { XCTFail() } } } func testConnectionLostEvent() { reachability.newConnection = .wifi let e = expectation(description: "Waiting for `onEvent` to get called") listener.eventClosure = { event, producer in XCTAssertEqual(event as? NetworkEventProducer.NetworkEvent, NetworkEventProducer.NetworkEvent.connectionLost) e.fulfill() } reachability.newConnection = .unavailable waitForExpectations(timeout: 1) { e in if let _ = e { XCTFail() } } } func testConnectionChangedEvent() { reachability.newConnection = .wifi let e = expectation(description: "Waiting for `onEvent` to get called") listener.eventClosure = { event, producer in XCTAssertEqual(event as? NetworkEventProducer.NetworkEvent, NetworkEventProducer.NetworkEvent.networkChanged) e.fulfill() } reachability.newConnection = .cellular waitForExpectations(timeout: 1) { e in if let _ = e { XCTFail() } } } }
28.88785
81
0.611776
895d974a444c014b8ca309d808a2412c5cab7007
58,292
// // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if !os(Windows) #if os(Android) && (arch(i386) || arch(arm)) // struct stat.st_mode is UInt32 internal func &(left: UInt32, right: mode_t) -> mode_t { return mode_t(left) & right } #endif import CoreFoundation extension FileManager { internal func _mountedVolumeURLs(includingResourceValuesForKeys propertyKeys: [URLResourceKey]?, options: VolumeEnumerationOptions = []) -> [URL]? { var urls: [URL] = [] #if os(Linux) || os(Android) guard let procMounts = try? String(contentsOfFile: "/proc/mounts", encoding: .utf8) else { return nil } urls = [] for line in procMounts.components(separatedBy: "\n") { let mountPoint = line.components(separatedBy: " ") if mountPoint.count > 2 { urls.append(URL(fileURLWithPath: mountPoint[1], isDirectory: true)) } } #elseif canImport(Darwin) func mountPoints(_ statBufs: UnsafePointer<statfs>, _ fsCount: Int) -> [URL] { var urls: [URL] = [] for fsIndex in 0..<fsCount { var fs = statBufs.advanced(by: fsIndex).pointee if options.contains(.skipHiddenVolumes) && fs.f_flags & UInt32(MNT_DONTBROWSE) != 0 { continue } let mountPoint = withUnsafePointer(to: &fs.f_mntonname.0) { (ptr: UnsafePointer<Int8>) -> String in return string(withFileSystemRepresentation: ptr, length: strlen(ptr)) } urls.append(URL(fileURLWithPath: mountPoint, isDirectory: true)) } return urls } if #available(OSX 10.13, *) { var statBufPtr: UnsafeMutablePointer<statfs>? let fsCount = getmntinfo_r_np(&statBufPtr, MNT_WAIT) guard let statBuf = statBufPtr, fsCount > 0 else { return nil } urls = mountPoints(statBuf, Int(fsCount)) free(statBufPtr) } else { var fsCount = getfsstat(nil, 0, MNT_WAIT) guard fsCount > 0 else { return nil } let statBuf = UnsafeMutablePointer<statfs>.allocate(capacity: Int(fsCount)) defer { statBuf.deallocate() } fsCount = getfsstat(statBuf, fsCount * Int32(MemoryLayout<statfs>.stride), MNT_WAIT) guard fsCount > 0 else { return nil } urls = mountPoints(statBuf, Int(fsCount)) } #else #error("Requires a platform-specific implementation") #endif return urls } internal func darwinPathURLs(for domain: _SearchPathDomain, system: String?, local: String?, network: String?, userHomeSubpath: String?) -> [URL] { switch domain { case .system: guard let path = system else { return [] } return [ URL(fileURLWithPath: path, isDirectory: true) ] case .local: guard let path = local else { return [] } return [ URL(fileURLWithPath: path, isDirectory: true) ] case .network: guard let path = network else { return [] } return [ URL(fileURLWithPath: path, isDirectory: true) ] case .user: guard let path = userHomeSubpath else { return [] } return [ URL(fileURLWithPath: path, isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] } } internal func darwinPathURLs(for domain: _SearchPathDomain, all: String, useLocalDirectoryForSystem: Bool = false) -> [URL] { switch domain { case .system: return [ URL(fileURLWithPath: useLocalDirectoryForSystem ? "/\(all)" : "/System/\(all)", isDirectory: true) ] case .local: return [ URL(fileURLWithPath: "/\(all)", isDirectory: true) ] case .network: return [ URL(fileURLWithPath: "/Network/\(all)", isDirectory: true) ] case .user: return [ URL(fileURLWithPath: all, isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] } } internal func _urls(for directory: SearchPathDirectory, in domainMask: SearchPathDomainMask) -> [URL] { let domains = _SearchPathDomain.allInSearchOrder(from: domainMask) var urls: [URL] = [] // We are going to return appropriate paths on Darwin, but [] on platforms that do not have comparable locations. // For example, on FHS/XDG systems, applications are not installed in a single path. let useDarwinPaths: Bool if let envVar = ProcessInfo.processInfo.environment["_NSFileManagerUseXDGPathsForDirectoryDomains"] { useDarwinPaths = !NSString(string: envVar).boolValue } else { #if canImport(Darwin) useDarwinPaths = true #else useDarwinPaths = false #endif } for domain in domains { if useDarwinPaths { urls.append(contentsOf: darwinURLs(for: directory, in: domain)) } else { urls.append(contentsOf: xdgURLs(for: directory, in: domain)) } } return urls } internal func xdgURLs(for directory: SearchPathDirectory, in domain: _SearchPathDomain) -> [URL] { // FHS/XDG-compliant OSes: switch directory { case .autosavedInformationDirectory: let runtimePath = __SwiftValue.fetch(nonOptional: _CFXDGCreateDataHomePath()) as! String return [ URL(fileURLWithPath: "Autosave Information", isDirectory: true, relativeTo: URL(fileURLWithPath: runtimePath, isDirectory: true)) ] case .desktopDirectory: guard domain == .user else { return [] } return [ _XDGUserDirectory.desktop.url ] case .documentDirectory: guard domain == .user else { return [] } return [ _XDGUserDirectory.documents.url ] case .cachesDirectory: guard domain == .user else { return [] } let path = __SwiftValue.fetch(nonOptional: _CFXDGCreateCacheDirectoryPath()) as! String return [ URL(fileURLWithPath: path, isDirectory: true) ] case .applicationSupportDirectory: guard domain == .user else { return [] } let path = __SwiftValue.fetch(nonOptional: _CFXDGCreateDataHomePath()) as! String return [ URL(fileURLWithPath: path, isDirectory: true) ] case .downloadsDirectory: guard domain == .user else { return [] } return [ _XDGUserDirectory.download.url ] case .userDirectory: guard domain == .local else { return [] } return [ URL(fileURLWithPath: xdgHomeDirectory, isDirectory: true) ] case .moviesDirectory: return [ _XDGUserDirectory.videos.url ] case .musicDirectory: guard domain == .user else { return [] } return [ _XDGUserDirectory.music.url ] case .picturesDirectory: guard domain == .user else { return [] } return [ _XDGUserDirectory.pictures.url ] case .sharedPublicDirectory: guard domain == .user else { return [] } return [ _XDGUserDirectory.publicShare.url ] case .trashDirectory: let userTrashURL = URL(fileURLWithPath: ".Trash", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) if domain == .user || domain == .local { return [ userTrashURL ] } else { return [] } // None of these are supported outside of Darwin: case .applicationDirectory: fallthrough case .demoApplicationDirectory: fallthrough case .developerApplicationDirectory: fallthrough case .adminApplicationDirectory: fallthrough case .libraryDirectory: fallthrough case .developerDirectory: fallthrough case .documentationDirectory: fallthrough case .coreServiceDirectory: fallthrough case .inputMethodsDirectory: fallthrough case .preferencePanesDirectory: fallthrough case .applicationScriptsDirectory: fallthrough case .allApplicationsDirectory: fallthrough case .allLibrariesDirectory: fallthrough case .printerDescriptionDirectory: fallthrough case .itemReplacementDirectory: return [] } } internal func darwinURLs(for directory: SearchPathDirectory, in domain: _SearchPathDomain) -> [URL] { switch directory { case .applicationDirectory: return darwinPathURLs(for: domain, all: "Applications", useLocalDirectoryForSystem: true) case .demoApplicationDirectory: return darwinPathURLs(for: domain, all: "Demos", useLocalDirectoryForSystem: true) case .developerApplicationDirectory: return darwinPathURLs(for: domain, all: "Developer/Applications", useLocalDirectoryForSystem: true) case .adminApplicationDirectory: return darwinPathURLs(for: domain, all: "Applications/Utilities", useLocalDirectoryForSystem: true) case .libraryDirectory: return darwinPathURLs(for: domain, all: "Library") case .developerDirectory: return darwinPathURLs(for: domain, all: "Developer", useLocalDirectoryForSystem: true) case .documentationDirectory: return darwinPathURLs(for: domain, all: "Library/Documentation") case .coreServiceDirectory: return darwinPathURLs(for: domain, system: "/System/Library/CoreServices", local: nil, network: nil, userHomeSubpath: nil) case .autosavedInformationDirectory: return darwinPathURLs(for: domain, system: nil, local: nil, network: nil, userHomeSubpath: "Library/Autosave Information") case .inputMethodsDirectory: return darwinPathURLs(for: domain, all: "Library/Input Methods") case .preferencePanesDirectory: return darwinPathURLs(for: domain, system: "/System/Library/PreferencePanes", local: "/Library/PreferencePanes", network: nil, userHomeSubpath: "Library/PreferencePanes") case .applicationScriptsDirectory: // Only the ObjC Foundation can know where this is. return [] case .allApplicationsDirectory: var directories: [URL] = [] directories.append(contentsOf: darwinPathURLs(for: domain, all: "Applications", useLocalDirectoryForSystem: true)) directories.append(contentsOf: darwinPathURLs(for: domain, all: "Demos", useLocalDirectoryForSystem: true)) directories.append(contentsOf: darwinPathURLs(for: domain, all: "Developer/Applications", useLocalDirectoryForSystem: true)) directories.append(contentsOf: darwinPathURLs(for: domain, all: "Applications/Utilities", useLocalDirectoryForSystem: true)) return directories case .allLibrariesDirectory: var directories: [URL] = [] directories.append(contentsOf: darwinPathURLs(for: domain, all: "Library")) directories.append(contentsOf: darwinPathURLs(for: domain, all: "Developer")) return directories case .printerDescriptionDirectory: guard domain == .system else { return [] } return [ URL(fileURLWithPath: "/System/Library/Printers/PPD", isDirectory: true) ] case .desktopDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Desktop", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .documentDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Documents", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .cachesDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Library/Caches", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .applicationSupportDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Library/Application Support", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .downloadsDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Downloads", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .userDirectory: return darwinPathURLs(for: domain, system: nil, local: "/Users", network: "/Network/Users", userHomeSubpath: nil) case .moviesDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Movies", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .musicDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Music", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .picturesDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Pictures", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .sharedPublicDirectory: guard domain == .user else { return [] } return [ URL(fileURLWithPath: "Public", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) ] case .trashDirectory: let userTrashURL = URL(fileURLWithPath: ".Trash", isDirectory: true, relativeTo: URL(fileURLWithPath: NSHomeDirectory(), isDirectory: true)) if domain == .user || domain == .local { return [ userTrashURL ] } else { return [] } case .itemReplacementDirectory: // This directory is only returned by url(for:in:appropriateFor:create:) return [] } } internal func _createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws { try _fileSystemRepresentation(withPath: path, { pathFsRep in if createIntermediates { var isDir: ObjCBool = false if !fileExists(atPath: path, isDirectory: &isDir) { let parent = path._nsObject.deletingLastPathComponent if !parent.isEmpty && !fileExists(atPath: parent, isDirectory: &isDir) { try createDirectory(atPath: parent, withIntermediateDirectories: true, attributes: attributes) } if mkdir(pathFsRep, S_IRWXU | S_IRWXG | S_IRWXO) != 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else if let attr = attributes { try self.setAttributes(attr, ofItemAtPath: path) } } else if isDir.boolValue { return } else { throw _NSErrorWithErrno(EEXIST, reading: false, path: path) } } else { if mkdir(pathFsRep, S_IRWXU | S_IRWXG | S_IRWXO) != 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else if let attr = attributes { try self.setAttributes(attr, ofItemAtPath: path) } } }) } internal func _contentsOfDir(atPath path: String, _ closure: (String, Int32) throws -> () ) throws { try _fileSystemRepresentation(withPath: path) { fsRep in guard let dir = opendir(fsRep) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue, userInfo: [NSFilePathErrorKey: path, "NSUserStringVariant": NSArray(object: "Folder")]) } defer { closedir(dir) } var entry = dirent() var result: UnsafeMutablePointer<dirent>? = nil while readdir_r(dir, &entry, &result) == 0 { guard result != nil else { return } let length = Int(_direntNameLength(&entry)) let entryName = withUnsafePointer(to: &entry.d_name) { (ptr) -> String in let namePtr = UnsafeRawPointer(ptr).assumingMemoryBound(to: CChar.self) return string(withFileSystemRepresentation: namePtr, length: length) } if entryName != "." && entryName != ".." { let entryType = Int32(entry.d_type) try closure(entryName, entryType) } } } } internal func _subpathsOfDirectory(atPath path: String) throws -> [String] { var contents: [String] = [] try _contentsOfDir(atPath: path, { (entryName, entryType) throws in contents.append(entryName) if entryType == DT_DIR { let subPath: String = path + "/" + entryName let entries = try subpathsOfDirectory(atPath: subPath) contents.append(contentsOf: entries.map({file in "\(entryName)/\(file)"})) } }) return contents } internal func _attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey : Any] { return try _attributesOfFileSystemIncludingBlockSize(forPath: path).attributes } internal func _attributesOfFileSystemIncludingBlockSize(forPath path: String) throws -> (attributes: [FileAttributeKey : Any], blockSize: UInt64?) { var result: [FileAttributeKey:Any] = [:] var finalBlockSize: UInt64? try _fileSystemRepresentation(withPath: path) { fsRep in // statvfs(2) doesn't support 64bit inode on Darwin (apfs), fallback to statfs(2) #if canImport(Darwin) var s = statfs() guard statfs(fsRep, &s) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: path) } #else var s = statvfs() guard statvfs(fsRep, &s) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: path) } #endif #if canImport(Darwin) let blockSize = UInt64(s.f_bsize) result[.systemNumber] = NSNumber(value: UInt64(s.f_fsid.val.0)) #else let blockSize = UInt64(s.f_frsize) result[.systemNumber] = NSNumber(value: UInt64(s.f_fsid)) #endif result[.systemSize] = NSNumber(value: blockSize * UInt64(s.f_blocks)) result[.systemFreeSize] = NSNumber(value: blockSize * UInt64(s.f_bavail)) result[.systemNodes] = NSNumber(value: UInt64(s.f_files)) result[.systemFreeNodes] = NSNumber(value: UInt64(s.f_ffree)) finalBlockSize = blockSize } return (attributes: result, blockSize: finalBlockSize) } internal func _createSymbolicLink(atPath path: String, withDestinationPath destPath: String) throws { try _fileSystemRepresentation(withPath: path, andPath: destPath, { guard symlink($1, $0) == 0 else { throw _NSErrorWithErrno(errno, reading: false, path: path) } }) } /* destinationOfSymbolicLinkAtPath:error: returns a String containing the path of the item pointed at by the symlink specified by 'path'. If this method returns 'nil', an NSError will be thrown. This method replaces pathContentOfSymbolicLinkAtPath: */ internal func _destinationOfSymbolicLink(atPath path: String) throws -> String { let bufSize = Int(PATH_MAX + 1) var buf = [Int8](repeating: 0, count: bufSize) let len = try _fileSystemRepresentation(withPath: path) { readlink($0, &buf, bufSize) } if len < 0 { throw _NSErrorWithErrno(errno, reading: true, path: path) } return self.string(withFileSystemRepresentation: buf, length: Int(len)) } /* Returns a String with a canonicalized path for the element at the specified path. */ internal func _canonicalizedPath(toFileAtPath path: String) throws -> String { let bufSize = Int(PATH_MAX + 1) var buf = [Int8](repeating: 0, count: bufSize) let done = try _fileSystemRepresentation(withPath: path) { realpath($0, &buf) != nil } if !done { throw _NSErrorWithErrno(errno, reading: true, path: path) } return self.string(withFileSystemRepresentation: buf, length: strlen(buf)) } internal func _readFrom(fd: Int32, toBuffer buffer: UnsafeMutablePointer<UInt8>, length bytesToRead: Int, filename: String) throws -> Int { var bytesRead = 0 repeat { bytesRead = numericCast(read(fd, buffer, numericCast(bytesToRead))) } while bytesRead < 0 && errno == EINTR guard bytesRead >= 0 else { throw _NSErrorWithErrno(errno, reading: true, path: filename) } return bytesRead } internal func _writeTo(fd: Int32, fromBuffer buffer : UnsafeMutablePointer<UInt8>, length bytesToWrite: Int, filename: String) throws { var bytesWritten = 0 while bytesWritten < bytesToWrite { var written = 0 let bytesLeftToWrite = bytesToWrite - bytesWritten repeat { written = numericCast(write(fd, buffer.advanced(by: bytesWritten), numericCast(bytesLeftToWrite))) } while written < 0 && errno == EINTR guard written >= 0 else { throw _NSErrorWithErrno(errno, reading: false, path: filename) } bytesWritten += written } } internal func _copyRegularFile(atPath srcPath: String, toPath dstPath: String, variant: String = "Copy") throws { let srcRep = try __fileSystemRepresentation(withPath: srcPath) defer { srcRep.deallocate() } let dstRep = try __fileSystemRepresentation(withPath: dstPath) defer { dstRep.deallocate() } var fileInfo = stat() guard stat(srcRep, &fileInfo) >= 0 else { throw _NSErrorWithErrno(errno, reading: true, path: srcPath, extraUserInfo: extraErrorInfo(srcPath: srcPath, dstPath: dstPath, userVariant: variant)) } let srcfd = open(srcRep, O_RDONLY) guard srcfd >= 0 else { throw _NSErrorWithErrno(errno, reading: true, path: srcPath, extraUserInfo: extraErrorInfo(srcPath: srcPath, dstPath: dstPath, userVariant: variant)) } defer { close(srcfd) } let dstfd = open(dstRep, O_WRONLY | O_CREAT | O_TRUNC, 0o666) guard dstfd >= 0 else { throw _NSErrorWithErrno(errno, reading: false, path: dstPath, extraUserInfo: extraErrorInfo(srcPath: srcPath, dstPath: dstPath, userVariant: variant)) } defer { close(dstfd) } // Set the file permissions using fchmod() instead of when open()ing to avoid umask() issues let permissions = fileInfo.st_mode & ~S_IFMT guard fchmod(dstfd, permissions) == 0 else { throw _NSErrorWithErrno(errno, reading: false, path: dstPath, extraUserInfo: extraErrorInfo(srcPath: srcPath, dstPath: dstPath, userVariant: variant)) } if fileInfo.st_size == 0 { // no copying required return } let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(fileInfo.st_blksize)) defer { buffer.deallocate() } // Casted to Int64 because fileInfo.st_size is 64 bits long even on 32 bit platforms var bytesRemaining = Int64(fileInfo.st_size) while bytesRemaining > 0 { let bytesToRead = min(bytesRemaining, Int64(fileInfo.st_blksize)) let bytesRead = try _readFrom(fd: srcfd, toBuffer: buffer, length: Int(bytesToRead), filename: srcPath) if bytesRead == 0 { // Early EOF return } try _writeTo(fd: dstfd, fromBuffer: buffer, length: bytesRead, filename: dstPath) bytesRemaining -= Int64(bytesRead) } } internal func _copySymlink(atPath srcPath: String, toPath dstPath: String, variant: String = "Copy") throws { let bufSize = Int(PATH_MAX) + 1 var buf = [Int8](repeating: 0, count: bufSize) try _fileSystemRepresentation(withPath: srcPath) { srcFsRep in let len = readlink(srcFsRep, &buf, bufSize) if len < 0 { throw _NSErrorWithErrno(errno, reading: true, path: srcPath, extraUserInfo: extraErrorInfo(srcPath: srcPath, dstPath: dstPath, userVariant: variant)) } try _fileSystemRepresentation(withPath: dstPath) { dstFsRep in if symlink(buf, dstFsRep) == -1 { throw _NSErrorWithErrno(errno, reading: false, path: dstPath, extraUserInfo: extraErrorInfo(srcPath: srcPath, dstPath: dstPath, userVariant: variant)) } } } } internal func _copyOrLinkDirectoryHelper(atPath srcPath: String, toPath dstPath: String, variant: String = "Copy", _ body: (String, String, FileAttributeType) throws -> ()) throws { let stat = try _lstatFile(atPath: srcPath) let fileType = FileAttributeType(statMode: mode_t(stat.st_mode)) if fileType == .typeDirectory { try createDirectory(atPath: dstPath, withIntermediateDirectories: false, attributes: nil) guard let enumerator = enumerator(atPath: srcPath) else { throw _NSErrorWithErrno(ENOENT, reading: true, path: srcPath) } while let item = enumerator.nextObject() as? String { let src = srcPath + "/" + item let dst = dstPath + "/" + item if let stat = try? _lstatFile(atPath: src) { let fileType = FileAttributeType(statMode: mode_t(stat.st_mode)) if fileType == .typeDirectory { try createDirectory(atPath: dst, withIntermediateDirectories: false, attributes: nil) } else { try body(src, dst, fileType) } } } } else { try body(srcPath, dstPath, fileType) } } internal func _moveItem(atPath srcPath: String, toPath dstPath: String, isURL: Bool) throws { guard shouldMoveItemAtPath(srcPath, toPath: dstPath, isURL: isURL) else { return } guard !self.fileExists(atPath: dstPath) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteFileExists.rawValue, userInfo: [NSFilePathErrorKey : NSString(dstPath)]) } try _fileSystemRepresentation(withPath: srcPath, andPath: dstPath, { if rename($0, $1) != 0 { if errno == EXDEV { try _copyOrLinkDirectoryHelper(atPath: srcPath, toPath: dstPath, variant: "Move") { (srcPath, dstPath, fileType) in do { switch fileType { case .typeRegular: try _copyRegularFile(atPath: srcPath, toPath: dstPath, variant: "Move") case .typeSymbolicLink: try _copySymlink(atPath: srcPath, toPath: dstPath, variant: "Move") default: break } } catch { if !shouldProceedAfterError(error, movingItemAtPath: srcPath, toPath: dstPath, isURL: isURL) { throw error } } } // Remove source directory/file after successful moving try _removeItem(atPath: srcPath, isURL: isURL, alreadyConfirmed: true) } else { throw _NSErrorWithErrno(errno, reading: false, path: srcPath, extraUserInfo: extraErrorInfo(srcPath: srcPath, dstPath: dstPath, userVariant: "Move")) } } }) } internal func _linkItem(atPath srcPath: String, toPath dstPath: String, isURL: Bool) throws { try _copyOrLinkDirectoryHelper(atPath: srcPath, toPath: dstPath) { (srcPath, dstPath, fileType) in guard shouldLinkItemAtPath(srcPath, toPath: dstPath, isURL: isURL) else { return } do { switch fileType { case .typeRegular: try _fileSystemRepresentation(withPath: srcPath, andPath: dstPath, { if link($0, $1) == -1 { throw _NSErrorWithErrno(errno, reading: false, path: srcPath) } }) case .typeSymbolicLink: try _copySymlink(atPath: srcPath, toPath: dstPath) default: break } } catch { if !shouldProceedAfterError(error, linkingItemAtPath: srcPath, toPath: dstPath, isURL: isURL) { throw error } } } } internal func _removeItem(atPath path: String, isURL: Bool, alreadyConfirmed: Bool = false) throws { guard alreadyConfirmed || shouldRemoveItemAtPath(path, isURL: isURL) else { return } try _fileSystemRepresentation(withPath: path, { fsRep in if rmdir(fsRep) == 0 { return } else if errno == ENOTEMPTY { let ps = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 2) ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) ps.advanced(by: 1).initialize(to: nil) let stream = fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR | FTS_NOSTAT, nil) ps.deinitialize(count: 2) ps.deallocate() if stream != nil { defer { fts_close(stream) } while let current = fts_read(stream)?.pointee { let itemPath = string(withFileSystemRepresentation: current.fts_path, length: Int(current.fts_pathlen)) guard alreadyConfirmed || shouldRemoveItemAtPath(itemPath, isURL: isURL) else { continue } do { switch Int32(current.fts_info) { case FTS_DEFAULT, FTS_F, FTS_NSOK, FTS_SL, FTS_SLNONE: if unlink(current.fts_path) == -1 { throw _NSErrorWithErrno(errno, reading: false, path: itemPath) } case FTS_DP: if rmdir(current.fts_path) == -1 { throw _NSErrorWithErrno(errno, reading: false, path: itemPath) } case FTS_DNR, FTS_ERR, FTS_NS: throw _NSErrorWithErrno(current.fts_errno, reading: false, path: itemPath) default: break } } catch { if !shouldProceedAfterError(error, removingItemAtPath: itemPath, isURL: isURL) { throw error } } } } else { let _ = _NSErrorWithErrno(ENOTEMPTY, reading: false, path: path) } } else if errno != ENOTDIR { throw _NSErrorWithErrno(errno, reading: false, path: path) } else if unlink(fsRep) != 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } }) } internal func _currentDirectoryPath() -> String { let length = Int(PATH_MAX) + 1 var buf = [Int8](repeating: 0, count: length) getcwd(&buf, length) return string(withFileSystemRepresentation: buf, length: Int(strlen(buf))) } @discardableResult internal func _changeCurrentDirectoryPath(_ path: String) -> Bool { do { return try _fileSystemRepresentation(withPath: path, { chdir($0) == 0 }) } catch { return false } } internal func _fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool { do { return try _fileSystemRepresentation(withPath: path, { fsRep in var s = try _lstatFile(atPath: path, withFileSystemRepresentation: fsRep) if (s.st_mode & S_IFMT) == S_IFLNK { // don't chase the link for this magic case -- we might be /Net/foo // which is a symlink to /private/Net/foo which is not yet mounted... if isDirectory == nil && (s.st_mode & S_ISVTX) == S_ISVTX { return true } // chase the link; too bad if it is a slink to /Net/foo guard stat(fsRep, &s) >= 0 else { return false } } if let isDirectory = isDirectory { isDirectory.pointee = ObjCBool((s.st_mode & S_IFMT) == S_IFDIR) } return true }) } catch { return false } } internal func _isReadableFile(atPath path: String) -> Bool { do { return try _fileSystemRepresentation(withPath: path, { access($0, R_OK) == 0 }) } catch { return false } } internal func _isWritableFile(atPath path: String) -> Bool { do { return try _fileSystemRepresentation(withPath: path, { access($0, W_OK) == 0 }) } catch { return false } } internal func _isExecutableFile(atPath path: String) -> Bool { do { return try _fileSystemRepresentation(withPath: path, { access($0, X_OK) == 0 }) } catch { return false } } /** - parameters: - path: The path to the file we are trying to determine is deletable. - returns: `true` if the file is deletable, `false` otherwise. */ internal func _isDeletableFile(atPath path: String) -> Bool { guard path != "" else { return true } // This matches Darwin even though its probably the wrong response // Get the parent directory of supplied path let parent = path._nsObject.deletingLastPathComponent do { return try _fileSystemRepresentation(withPath: parent, andPath: path, { parentFsRep, fsRep in // Check the parent directory is writeable, else return false. guard access(parentFsRep, W_OK) == 0 else { return false } // Stat the parent directory, if that fails, return false. let parentS = try _lstatFile(atPath: path, withFileSystemRepresentation: parentFsRep) // Check if the parent is 'sticky' if it exists. if (parentS.st_mode & S_ISVTX) == S_ISVTX { let s = try _lstatFile(atPath: path, withFileSystemRepresentation: fsRep) // If the current user owns the file, return true. return s.st_uid == getuid() } // Return true as the best guess. return true }) } catch { return false } } private func _compareFiles(withFileSystemRepresentation file1Rep: UnsafePointer<Int8>, andFileSystemRepresentation file2Rep: UnsafePointer<Int8>, size: Int64, bufSize: Int) -> Bool { guard let file1 = FileHandle(fileSystemRepresentation: file1Rep, flags: O_RDONLY, createMode: 0) else { return false } guard let file2 = FileHandle(fileSystemRepresentation: file2Rep, flags: O_RDONLY, createMode: 0) else { return false } var buffer1 = UnsafeMutablePointer<UInt8>.allocate(capacity: bufSize) var buffer2 = UnsafeMutablePointer<UInt8>.allocate(capacity: bufSize) defer { buffer1.deallocate() buffer2.deallocate() } var bytesLeft = size while bytesLeft > 0 { let bytesToRead = Int(min(Int64(bufSize), bytesLeft)) guard let file1BytesRead = try? file1._readBytes(into: buffer1, length: bytesToRead), file1BytesRead == bytesToRead else { return false } guard let file2BytesRead = try? file2._readBytes(into: buffer2, length: bytesToRead), file2BytesRead == bytesToRead else { return false } guard memcmp(buffer1, buffer2, bytesToRead) == 0 else { return false } bytesLeft -= Int64(bytesToRead) } return true } private func _compareSymlinks(withFileSystemRepresentation file1Rep: UnsafePointer<Int8>, andFileSystemRepresentation file2Rep: UnsafePointer<Int8>, size: Int64) -> Bool { let bufSize = Int(size) let buffer1 = UnsafeMutablePointer<CChar>.allocate(capacity: bufSize) let buffer2 = UnsafeMutablePointer<CChar>.allocate(capacity: bufSize) let size1 = readlink(file1Rep, buffer1, bufSize) let size2 = readlink(file2Rep, buffer2, bufSize) let compare: Bool if size1 < 0 || size2 < 0 || size1 != size || size1 != size2 { compare = false } else { compare = memcmp(buffer1, buffer2, size1) == 0 } buffer1.deallocate() buffer2.deallocate() return compare } internal func _lstatFile(atPath path: String, withFileSystemRepresentation fsRep: UnsafePointer<Int8>? = nil) throws -> stat { let _fsRep: UnsafePointer<Int8> if fsRep == nil { _fsRep = try __fileSystemRepresentation(withPath: path) } else { _fsRep = fsRep! } defer { if fsRep == nil { _fsRep.deallocate() } } var statInfo = stat() guard lstat(_fsRep, &statInfo) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: path) } return statInfo } #if os(Linux) // This is only used on Linux and the only extra information it returns in addition // to a normal stat() call is the file creation date (stx_btime). It is only // used by attributesOfItem(atPath:) which is why the return is a simple stat() // structure and optional creation date. internal func _statxFile(atPath path: String) throws -> (stat, Date?) { return try _fileSystemRepresentation(withPath: path) { fsRep in if supportsStatx { var statInfo = stat() var btime = timespec() guard _stat_with_btime(fsRep, &statInfo, &btime) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: path) } let sec = btime.tv_sec let nsec = btime.tv_nsec let creationDate: Date? if sec == 0 && nsec == 0 { creationDate = nil } else { let ti = (TimeInterval(sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(nsec)) creationDate = Date(timeIntervalSinceReferenceDate: ti) } return (statInfo, creationDate) } else { // fallback if statx() is unavailable or fails let statInfo = try _lstatFile(atPath: path, withFileSystemRepresentation: fsRep) return (statInfo, nil) } } } #endif /* -contentsEqualAtPath:andPath: does not take into account data stored in the resource fork or filesystem extended attributes. */ internal func _contentsEqual(atPath path1: String, andPath path2: String) -> Bool { do { let fsRep1 = try __fileSystemRepresentation(withPath: path1) defer { fsRep1.deallocate() } let file1 = try _lstatFile(atPath: path1, withFileSystemRepresentation: fsRep1) let file1Type = file1.st_mode & S_IFMT // Don't use access() for symlinks as only the contents should be checked even // if the symlink doesnt point to an actual file, but access() will always try // to resolve the link and fail if the destination is not found if path1 == path2 && file1Type != S_IFLNK { return access(fsRep1, R_OK) == 0 } let fsRep2 = try __fileSystemRepresentation(withPath: path2) defer { fsRep2.deallocate() } let file2 = try _lstatFile(atPath: path2, withFileSystemRepresentation: fsRep2) let file2Type = file2.st_mode & S_IFMT // Are paths the same type: file, directory, symbolic link etc. guard file1Type == file2Type else { return false } if file1Type == S_IFCHR || file1Type == S_IFBLK { // For character devices, just check the major/minor pair is the same. return _dev_major(dev_t(file1.st_rdev)) == _dev_major(dev_t(file2.st_rdev)) && _dev_minor(dev_t(file1.st_rdev)) == _dev_minor(dev_t(file2.st_rdev)) } // If both paths point to the same device/inode or they are both zero length // then they are considered equal so just check readability. if (file1.st_dev == file2.st_dev && file1.st_ino == file2.st_ino) || (file1.st_size == 0 && file2.st_size == 0) { return access(fsRep1, R_OK) == 0 && access(fsRep2, R_OK) == 0 } if file1Type == S_IFREG { // Regular files and symlinks should at least have the same filesize if contents are equal. guard file1.st_size == file2.st_size else { return false } return _compareFiles(withFileSystemRepresentation: path1, andFileSystemRepresentation: path2, size: Int64(file1.st_size), bufSize: Int(file1.st_blksize)) } else if file1Type == S_IFLNK { return _compareSymlinks(withFileSystemRepresentation: fsRep1, andFileSystemRepresentation: fsRep2, size: Int64(file1.st_size)) } else if file1Type == S_IFDIR { return _compareDirectories(atPath: path1, andPath: path2) } // Don't know how to compare other file types. return false } catch { return false } } internal func _appendSymlinkDestination(_ dest: String, toPath: String) -> String { let isAbsolutePath: Bool = dest.hasPrefix("/") if isAbsolutePath { return dest } let temp = toPath._bridgeToObjectiveC().deletingLastPathComponent return temp._bridgeToObjectiveC().appendingPathComponent(dest) } internal class NSURLDirectoryEnumerator : DirectoryEnumerator { var _url : URL var _options : FileManager.DirectoryEnumerationOptions var _errorHandler : ((URL, Error) -> Bool)? var _stream : UnsafeMutablePointer<FTS>? = nil var _current : UnsafeMutablePointer<FTSENT>? = nil var _rootError : Error? = nil var _gotRoot : Bool = false // See @escaping comments above. init(url: URL, options: FileManager.DirectoryEnumerationOptions, errorHandler: (/* @escaping */ (URL, Error) -> Bool)?) { _url = url _options = options _errorHandler = errorHandler let fm = FileManager.default do { guard fm.fileExists(atPath: _url.path) else { throw _NSErrorWithErrno(ENOENT, reading: true, url: url) } _stream = try FileManager.default._fileSystemRepresentation(withPath: _url.path) { fsRep in let ps = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 2) defer { ps.deallocate() } ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) ps.advanced(by: 1).initialize(to: nil) return fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR | FTS_NOSTAT, nil) } if _stream == nil { throw _NSErrorWithErrno(errno, reading: true, url: url) } } catch { _rootError = error } } deinit { if let stream = _stream { fts_close(stream) } } override func nextObject() -> Any? { func match(filename: String, to options: DirectoryEnumerationOptions, isDir: Bool) -> (Bool, Bool) { var showFile = true var skipDescendants = false if isDir { if options.contains(.skipsSubdirectoryDescendants) { skipDescendants = true } // Ignore .skipsPackageDescendants } if options.contains(.skipsHiddenFiles) && (filename[filename._startOfLastPathComponent] == ".") { showFile = false skipDescendants = true } return (showFile, skipDescendants) } if let stream = _stream { if !_gotRoot { _gotRoot = true // Skip the root. _current = fts_read(stream) } _current = fts_read(stream) while let current = _current { let filename = FileManager.default.string(withFileSystemRepresentation: current.pointee.fts_path, length: Int(current.pointee.fts_pathlen)) switch Int32(current.pointee.fts_info) { case FTS_D: let (showFile, skipDescendants) = match(filename: filename, to: _options, isDir: true) if skipDescendants { fts_set(_stream, _current, FTS_SKIP) } if showFile { return URL(fileURLWithPath: filename, isDirectory: true) } case FTS_DEFAULT, FTS_F, FTS_NSOK, FTS_SL, FTS_SLNONE: let (showFile, _) = match(filename: filename, to: _options, isDir: false) if showFile { return URL(fileURLWithPath: filename, isDirectory: false) } case FTS_DNR, FTS_ERR, FTS_NS: let keepGoing: Bool if let handler = _errorHandler { keepGoing = handler(URL(fileURLWithPath: filename), _NSErrorWithErrno(current.pointee.fts_errno, reading: true)) } else { keepGoing = true } if !keepGoing { fts_close(stream) _stream = nil return nil } default: break } _current = fts_read(stream) } // TODO: Error handling if fts_read fails. } else if let error = _rootError { // Was there an error opening the stream? if let handler = _errorHandler { let _ = handler(_url, error) } } return nil } override var level: Int { return Int(_current?.pointee.fts_level ?? 0) } override func skipDescendants() { if let stream = _stream, let current = _current { fts_set(stream, current, FTS_SKIP) } } override var directoryAttributes : [FileAttributeKey : Any]? { return nil } override var fileAttributes: [FileAttributeKey : Any]? { return nil } } internal func _updateTimes(atPath path: String, withFileSystemRepresentation fsr: UnsafePointer<Int8>, creationTime: Date? = nil, accessTime: Date? = nil, modificationTime: Date? = nil) throws { let stat = try _lstatFile(atPath: path, withFileSystemRepresentation: fsr) let accessDate = accessTime ?? stat.lastAccessDate let modificationDate = modificationTime ?? stat.lastModificationDate let (accessTimeSince1970Seconds, accessTimeSince1970FractionsOfSecond) = modf(accessDate.timeIntervalSince1970) let accessTimeval = timeval(tv_sec: time_t(accessTimeSince1970Seconds), tv_usec: suseconds_t(1.0e9 * accessTimeSince1970FractionsOfSecond)) let (modificationTimeSince1970Seconds, modificationTimeSince1970FractionsOfSecond) = modf(modificationDate.timeIntervalSince1970) let modificationTimeval = timeval(tv_sec: time_t(modificationTimeSince1970Seconds), tv_usec: suseconds_t(1.0e9 * modificationTimeSince1970FractionsOfSecond)) let array = [accessTimeval, modificationTimeval] let errnoValue = array.withUnsafeBufferPointer { (bytes) -> Int32? in if utimes(fsr, bytes.baseAddress) < 0 { return errno } else { return nil } } if let error = errnoValue { throw _NSErrorWithErrno(error, reading: false, path: path) } } internal func _replaceItem(at originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String?, options: ItemReplacementOptions = [], allowPlatformSpecificSyscalls: Bool = true) throws -> URL? { // 1. Make a backup, if asked to. var backupItemURL: URL? if let backupItemName = backupItemName { let url = originalItemURL.deletingLastPathComponent().appendingPathComponent(backupItemName) try copyItem(at: originalItemURL, to: url) backupItemURL = url } // 2. Make sure we have a copy of the original attributes if we're being asked to preserve them (the default) let originalAttributes = try attributesOfItem(atPath: originalItemURL.path) let newAttributes = try attributesOfItem(atPath: newItemURL.path) func applyPostprocessingRequiredByOptions() throws { if !options.contains(.usingNewMetadataOnly) { var attributesToReapply: [FileAttributeKey: Any] = [:] attributesToReapply[.creationDate] = originalAttributes[.creationDate] attributesToReapply[.posixPermissions] = originalAttributes[.posixPermissions] try setAttributes(attributesToReapply, ofItemAtPath: originalItemURL.path) } // As the very last step, if not explicitly asked to keep the backup, remove it. if let backupItemURL = backupItemURL, !options.contains(.withoutDeletingBackupItem) { try removeItem(at: backupItemURL) } } if allowPlatformSpecificSyscalls { // First, a little OS-specific detour. // Blindly try these operations first, and fall back to the non-OS-specific code below if they all fail. #if canImport(Darwin) do { let finalErrno = originalItemURL.withUnsafeFileSystemRepresentation { (originalFS) -> Int32? in return newItemURL.withUnsafeFileSystemRepresentation { (newItemFS) -> Int32? in // Note that Darwin allows swapping a file with a directory this way. if renameatx_np(AT_FDCWD, originalFS, AT_FDCWD, newItemFS, UInt32(RENAME_SWAP)) == 0 { return nil } else { return errno } } } if let finalErrno = finalErrno, finalErrno != ENOTSUP { throw _NSErrorWithErrno(finalErrno, reading: false, url: originalItemURL) } else if finalErrno == nil { try applyPostprocessingRequiredByOptions() return originalItemURL } } #endif #if canImport(Glibc) do { let finalErrno = originalItemURL.withUnsafeFileSystemRepresentation { (originalFS) -> Int32? in return newItemURL.withUnsafeFileSystemRepresentation { (newItemFS) -> Int32? in if let originalFS = originalFS, let newItemFS = newItemFS { #if os(Linux) if _CFHasRenameat2 && kernelSupportsRenameat2 { if _CF_renameat2(AT_FDCWD, originalFS, AT_FDCWD, newItemFS, _CF_renameat2_RENAME_EXCHANGE) == 0 { return nil } else { return errno } } #endif if renameat(AT_FDCWD, originalFS, AT_FDCWD, newItemFS) == 0 { return nil } else { return errno } } else { return Int32(EINVAL) } } } // ENOTDIR is raised if the objects are directories; EINVAL may indicate that the filesystem does not support the operation. if let finalErrno = finalErrno, finalErrno != ENOTDIR && finalErrno != EINVAL { throw _NSErrorWithErrno(finalErrno, reading: false, url: originalItemURL) } else if finalErrno == nil { try applyPostprocessingRequiredByOptions() return originalItemURL } } #endif } // 3. Replace! // Are they both regular files? let originalType = originalAttributes[.type] as? FileAttributeType let newType = newAttributes[.type] as? FileAttributeType if originalType == newType, originalType == .typeRegular { let finalErrno = originalItemURL.withUnsafeFileSystemRepresentation { (originalFS) -> Int32? in return newItemURL.withUnsafeFileSystemRepresentation { (newItemFS) -> Int32? in // This is an atomic operation in many OSes, but is not guaranteed to be atomic by the standard. if rename(newItemFS, originalFS) == 0 { return nil } else { return errno } } } if let theErrno = finalErrno { throw _NSErrorWithErrno(theErrno, reading: false, url: originalItemURL) } } else { // Only perform a replacement of different object kinds nonatomically. let uniqueName = UUID().uuidString let tombstoneURL = newItemURL.deletingLastPathComponent().appendingPathComponent(uniqueName) try moveItem(at: originalItemURL, to: tombstoneURL) try moveItem(at: newItemURL, to: originalItemURL) try removeItem(at: tombstoneURL) } // 4. Reapply attributes if asked to preserve, and delete the backup if not asked otherwise. try applyPostprocessingRequiredByOptions() return originalItemURL } } extension FileManager.NSPathDirectoryEnumerator { internal func _nextObject() -> Any? { let o = innerEnumerator.nextObject() guard let url = o as? URL else { return nil } let path = url.path.replacingOccurrences(of: baseURL.path+"/", with: "") _currentItemPath = path return _currentItemPath } } #endif
43.86155
207
0.568997
1da1734f47f368989db03434dae81cca1c3ca2c0
580
// // AppDelegate.swift // SwiftSound // // Created by Philip Hansen on 03/11/15. // Copyright © 2015 Philip Hansen. Licensed under the MIT Licnse. // See the LICENSE file in the repository root for details. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
20.714286
71
0.722414
e2226a5f424d4b6351b3900b356fd21a28f0ca9b
36,637
import SwiftUI import Combine import Carbon import Defaults import Regex enum SSApp { static let id = Bundle.main.bundleIdentifier! static let name = Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as! String static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String static let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String static let versionWithBuild = "\(version) (\(build))" static let icon = NSApp.applicationIconImage! static let url = Bundle.main.bundleURL static func quit() { NSApp.terminate(nil) } static let isFirstLaunch: Bool = { let key = "SS_hasLaunched" if UserDefaults.standard.bool(forKey: key) { return false } else { UserDefaults.standard.set(true, forKey: key) return true } }() static func openSendFeedbackPage() { let metadata = """ \(SSApp.name) \(SSApp.versionWithBuild) - \(SSApp.id) macOS \(Device.osVersion) \(Device.hardwareModel) """ let query: [String: String] = [ "product": SSApp.name, "metadata": metadata ] URL("https://sindresorhus.com/feedback/").addingDictionaryAsQuery(query).open() } static var isDockIconVisible: Bool { get { NSApp.activationPolicy() == .regular } set { NSApp.setActivationPolicy(newValue ? .regular : .accessory) } } } extension SSApp { /// Manually show the SwiftUI settings window. static func showSettingsWindow() { if NSApp.activationPolicy() == .accessory { NSApp.activate(ignoringOtherApps: true) } // Run in the next runloop so it doesn't conflict with SwiftUI if run at startup. DispatchQueue.main.async { NSApp.sendAction(Selector(("showPreferencesWindow:")), to: nil, from: nil) } } } enum Device { static let osVersion: String = { let os = ProcessInfo.processInfo.operatingSystemVersion return "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)" }() static let hardwareModel: String = { var size = 0 sysctlbyname("hw.model", nil, &size, nil, 0) var model = [CChar](repeating: 0, count: size) sysctlbyname("hw.model", &model, &size, nil, 0) return String(cString: model) }() } private func escapeQuery(_ query: String) -> String { // From RFC 3986 let generalDelimiters = ":#[]@" let subDelimiters = "!$&'()*+,;=" var allowedCharacters = CharacterSet.urlQueryAllowed allowedCharacters.remove(charactersIn: generalDelimiters + subDelimiters) return query.addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? query } extension Dictionary where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral { var asQueryItems: [URLQueryItem] { map { URLQueryItem( name: escapeQuery($0 as! String), value: escapeQuery($1 as! String) ) } } var asQueryString: String { var components = URLComponents() components.queryItems = asQueryItems return components.query! } } extension URLComponents { mutating func addDictionaryAsQuery(_ dict: [String: String]) { percentEncodedQuery = dict.asQueryString } } extension URL { func addingDictionaryAsQuery(_ dict: [String: String]) -> Self { var components = URLComponents(url: self, resolvingAgainstBaseURL: false)! components.addDictionaryAsQuery(dict) return components.url ?? self } } @discardableResult func with<T>(_ value: T, update: (inout T) throws -> Void) rethrows -> T { var copy = value try update(&copy) return copy } extension AnyCancellable { private static var foreverStore = Set<AnyCancellable>() /** Stores this AnyCancellable forever. - Important: Only use this in singletons, for example, `AppDelegate`. Otherwise, it will create memory leaks. */ func storeForever() { store(in: &Self.foreverStore) } } extension String { var attributedString: NSAttributedString { NSAttributedString(string: self) } } extension NSAttributedString { /// Returns a `NSMutableAttributedString` version. func mutable() -> NSMutableAttributedString { // Force-casting here is safe as it can only be nil if there's no `mutableCopy` implementation, but we know there is for `NSMutableAttributedString`. // swiftlint:disable:next force_cast mutableCopy() as! NSMutableAttributedString } var nsRange: NSRange { NSRange(0..<length) } /// Get an attribute if it applies to the whole string. func attributeForWholeString(_ key: Key) -> Any? { guard length > 0 else { return nil } var foundRange = NSRange() let result = attribute(key, at: 0, longestEffectiveRange: &foundRange, in: nsRange) guard foundRange.length == length else { return nil } return result } /// The `.font` attribute for the whole string, falling back to the system font if none. /// - Note: It even handles if half the string has one attribute and the other half has another, as long as those attributes are identical. var font: NSFont { attributeForWholeString(.font) as? NSFont ?? .systemFont(ofSize: NSFont.systemFontSize) } /// - Important: This does not preserve font-related styles like bold and italic. func withFontSizeFast(_ fontSize: Double) -> NSAttributedString { addingAttributes([.font: font.withSize(CGFloat(fontSize))]) } func addingAttributes(_ attributes: [Key: Any]) -> NSAttributedString { let new = mutable() new.addAttributes(attributes, range: nsRange) return new } /// - Important: This does not preserve font-related styles like bold and italic. func withFont(_ font: NSFont) -> NSAttributedString { addingAttributes([.font: font]) } } extension NSView { func focus() { window?.makeFirstResponder(self) } func blur() { window?.makeFirstResponder(nil) } } final class LocalEventMonitor: ObservableObject { private let events: NSEvent.EventTypeMask private let callback: ((NSEvent) -> NSEvent?)? private weak var monitor: AnyObject? // swiftlint:disable:next private_subject let objectWillChange = PassthroughSubject<NSEvent, Never>() init( events: NSEvent.EventTypeMask, callback: ((NSEvent) -> NSEvent?)? = nil ) { self.events = events self.callback = callback } deinit { stop() } @discardableResult func start() -> Self { monitor = NSEvent.addLocalMonitorForEvents(matching: events) { [weak self] in guard let self = self else { return $0 } self.objectWillChange.send($0) return self.callback?($0) ?? $0 } as AnyObject return self } func stop() { guard let monitor = monitor else { return } NSEvent.removeMonitor(monitor) } } extension NSView { func constrainEdges(to view: NSView) { translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ leadingAnchor.constraint(equalTo: view.leadingAnchor), trailingAnchor.constraint(equalTo: view.trailingAnchor), topAnchor.constraint(equalTo: view.topAnchor), bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) } func constrainEdgesToSuperview() { guard let superview = superview else { assertionFailure("There is no superview for this view") return } constrainEdges(to: superview) } } extension NSColor { typealias RGBA = ( red: Double, green: Double, blue: Double, alpha: Double ) var rgba: RGBA { #if canImport(AppKit) guard let color = usingColorSpace(.extendedSRGB) else { assertionFailure("Unsupported color space") return RGBA(0, 0, 0, 0) } #elseif canImport(UIKit) let color = self #endif var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) return RGBA(red.double, green.double, blue.double, alpha.double) } } extension NSColor { typealias HSBA = (hue: Double, saturation: Double, brightness: Double, alpha: Double) var hsba: HSBA { #if canImport(AppKit) guard let color = usingColorSpace(.extendedSRGB) else { assertionFailure("Unsupported color space") return HSBA(0, 0, 0, 0) } #elseif canImport(UIKit) let color = self #endif var hue: CGFloat = 0 var saturation: CGFloat = 0 var brightness: CGFloat = 0 var alpha: CGFloat = 0 color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) return HSBA( hue: hue.double, saturation: saturation.double, brightness: brightness.double, alpha: alpha.double ) } } extension NSColor { typealias HSLA = ( hue: Double, saturation: Double, lightness: Double, alpha: Double ) /// - Important: Ensure you use a compatible color space, otherwise it will just be black. var hsla: HSLA { let hsba = self.hsba var saturation = hsba.saturation * hsba.brightness var lightness = (2.0 - hsba.saturation) * hsba.brightness let saturationDivider = (lightness <= 1.0 ? lightness : 2.0 - lightness) if saturationDivider != 0 { saturation /= saturationDivider } lightness /= 2.0 return HSLA( hue: hsba.hue, saturation: saturation, lightness: lightness, alpha: hsba.alpha ) } /** Create from HSL components. */ convenience init( colorSpace: NSColorSpace, hue: CGFloat, saturation: CGFloat, lightness: CGFloat, alpha: CGFloat ) { precondition( 0...1 ~= hue && 0...1 ~= saturation && 0...1 ~= lightness && 0...1 ~= alpha, "Input is out of range 0...1" ) let brightness = lightness + saturation * min(lightness, 1 - lightness) let newSaturation = brightness == 0 ? 0 : (2 * (1 - lightness / brightness)) self.init( colorSpace: colorSpace, hue: hue, saturation: newSaturation, brightness: brightness, alpha: alpha ) } } extension Color { /** Create a `Color` from HSL components. Assumes `extendedSRGB` input. */ init( hue: Double, saturation: Double, lightness: Double, opacity: Double ) { precondition( 0...1 ~= hue && 0...1 ~= saturation && 0...1 ~= lightness && 0...1 ~= opacity, "Input is out of range 0...1" ) let brightness = lightness + saturation * min(lightness, 1 - lightness) let newSaturation = brightness == 0 ? 0 : (2 * (1 - lightness / brightness)) self.init( hue: hue, saturation: newSaturation, brightness: brightness, opacity: opacity ) } } extension NSColor { private static let cssHSLRegex = Regex(#"^\s*hsla?\((?<hue>\d+)(?:deg)?[\s,]*(?<saturation>[\d.]+)%[\s,]*(?<lightness>[\d.]+)%\)\s*$"#) // TODO: Support `alpha` in HSL (both comma and `/` separated): https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hsl() // TODO: Write a lot of tests for the regex. /// Assumes `sRGB` color space. convenience init?(cssHSLString: String) { guard let match = Self.cssHSLRegex.firstMatch(in: cssHSLString), let hueString = match.group(named: "hue")?.value, let saturationString = match.group(named: "saturation")?.value, let lightnessString = match.group(named: "lightness")?.value, let hue = Double(hueString), let saturation = Double(saturationString), let lightness = Double(lightnessString), (0...360).contains(hue), (0...100).contains(saturation), (0...100).contains(lightness) else { return nil } self.init( colorSpace: .sRGB, hue: hue.cgFloat / 360, saturation: saturation.cgFloat / 100, lightness: lightness.cgFloat / 100, alpha: 1 ) } } extension NSColor { private static let cssRGBRegex = Regex(#"^\s*rgba?\((?<red>[\d.]+)[\s,]*(?<green>[\d.]+)[\s,]*(?<blue>[\d.]+)\)\s*$"#) // TODO: Need to handle `rgb(10%, 10%, 10%)`. // TODO: Support `alpha` in RGB (both comma and `/` separated): https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/hsl() // TODO: Write a lot of tests for the regex. /// Assumes `sRGB` color space. convenience init?(cssRGBString: String) { guard let match = Self.cssRGBRegex.firstMatch(in: cssRGBString), let redString = match.group(named: "red")?.value, let greenString = match.group(named: "green")?.value, let blueString = match.group(named: "blue")?.value, let red = Double(redString), let green = Double(greenString), let blue = Double(blueString), (0...255).contains(red), (0...255).contains(green), (0...255).contains(blue) else { return nil } self.init( srgbRed: red.cgFloat / 255, green: green.cgFloat / 255, blue: blue.cgFloat / 255, alpha: 1 ) } } extension NSColor { /** Create a color from a CSS color string in the format Hex, HSL, or RGB. Assumes `sRGB` color space. */ static func from(cssString: String) -> NSColor? { if let color = NSColor(hexString: cssString) { return color } if let color = NSColor(cssRGBString: cssString) { return color } if let color = NSColor(cssHSLString: cssString) { return color } return nil } } extension NSColor { /** Loosely gets a color from the pasteboard. It first tries to get an actual `NSColor` and then tries to parse a CSS string (ignoring leading/trailing whitespace) for Hex, HSL, and RGB. */ static func fromPasteboardGraceful(_ pasteboard: NSPasteboard) -> NSColor? { if let color = self.init(from: pasteboard) { return color } guard let string = pasteboard.string(forType: .string)?.trimmingCharacters(in: .whitespaces), let color = from(cssString: string) else { return nil } return color } } extension NSColor { /** ``` NSColor(hex: 0xFFFFFF) ``` */ convenience init(hex: Int, alpha: Double = 1) { self.init( red: CGFloat((hex >> 16) & 0xFF) / 255, green: CGFloat((hex >> 8) & 0xFF) / 255, blue: CGFloat(hex & 0xFF) / 255, alpha: CGFloat(alpha) ) } convenience init?(hexString: String, alpha: Double = 1) { var string = hexString if hexString.hasPrefix("#") { string = String(hexString.dropFirst()) } if string.count == 3 { string = string.map { "\($0)\($0)" }.joined() } guard let hex = Int(string, radix: 16) else { return nil } self.init(hex: hex, alpha: alpha) } /** - Important: Don't forget to convert it to the correct color space first. ``` NSColor(hexString: "#fefefe")!.hex //=> 0xFEFEFE ``` */ var hex: Int { #if canImport(AppKit) guard numberOfComponents == 4 else { assertionFailure() return 0x0 } #endif let red = Int((redComponent * 0xFF).rounded()) let green = Int((greenComponent * 0xFF).rounded()) let blue = Int((blueComponent * 0xFF).rounded()) return red << 16 | green << 8 | blue } /** - Important: Don't forget to convert it to the correct color space first. ``` NSColor(hexString: "#fefefe")!.hexString //=> "#fefefe" ``` */ var hexString: String { String(format: "#%06x", hex) } } extension NSColor { enum ColorStringFormat { case hex(isUppercased: Bool = false, hasPrefix: Bool = false) case hsl case rgb case hslLegacy case rgbLegacy } /// Format the color to a string using the given format. func format(_ format: ColorStringFormat) -> String { switch format { case .hex(let isUppercased, let hasPrefix): var string = hexString if isUppercased { string = string.uppercased() } if !hasPrefix { string = string.dropFirst().string } return string case .hsl: let hsla = self.hsla let hue = Int((hsla.hue * 360).rounded()) let saturation = Int((hsla.saturation * 100).rounded()) let lightness = Int((hsla.lightness * 100).rounded()) return String(format: "hsl(%ddeg %d%% %d%%)", hue, saturation, lightness) case .rgb: let rgba = self.rgba let red = Int((rgba.red * 0xFF).rounded()) let green = Int((rgba.green * 0xFF).rounded()) let blue = Int((rgba.blue * 0xFF).rounded()) return String(format: "rgb(%d %d %d)", red, green, blue) case .hslLegacy: let hsla = self.hsla let hue = Int((hsla.hue * 360).rounded()) let saturation = Int((hsla.saturation * 100).rounded()) let lightness = Int((hsla.lightness * 100).rounded()) return String(format: "hsl(%d, %d%%, %d%%)", hue, saturation, lightness) case .rgbLegacy: let rgba = self.rgba let red = Int((rgba.red * 0xFF).rounded()) let green = Int((rgba.green * 0xFF).rounded()) let blue = Int((rgba.blue * 0xFF).rounded()) return String(format: "rgb(%d, %d, %d)", red, green, blue) } } } extension StringProtocol { /// Makes it easier to deal with optional SubStrings. var string: String { String(self) } } extension NSPasteboard { func with(_ callback: (NSPasteboard) -> Void) { clearContents() callback(self) } } extension String { func copyToPasteboard() { NSPasteboard.general.with { $0.setString(self, forType: .string) } } } extension Double { /// Get a CGFloat from a Double. This makes it easier to work with optionals. var cgFloat: CGFloat { CGFloat(self) } } extension CGFloat { /// Get a Double from a CGFloat. This makes it easier to work with optionals. var double: Double { Double(self) } } extension Int { /// Get a Double from an Int. This makes it easier to work with optionals. var double: Double { Double(self) } /// Get a CGFloat from an Int. This makes it easier to work with optionals. var cgFloat: CGFloat { CGFloat(self) } } extension DispatchQueue { /** Performs the `execute` closure immediately if we're on the main thread or asynchronously puts it on the main thread otherwise. */ static func mainSafeAsync(execute work: @escaping () -> Void) { if Thread.isMainThread { work() } else { main.async(execute: work) } } } extension Binding where Value: Equatable { /** Get notified when the binding value changes to a different one. Can be useful to manually update non-reactive properties. ``` Toggle( "Foo", isOn: $foo.onChange { bar.isEnabled = $0 } ) ``` */ func onChange(_ action: @escaping (Value) -> Void) -> Self { .init( get: { wrappedValue }, set: { let oldValue = wrappedValue wrappedValue = $0 let newValue = wrappedValue if newValue != oldValue { action(newValue) } } ) } } extension Defaults { final class Observable<Value: Codable>: ObservableObject { let objectWillChange = ObservableObjectPublisher() private var observation: DefaultsObservation? private let key: Defaults.Key<Value> var value: Value { get { Defaults[key] } set { objectWillChange.send() Defaults[key] = newValue } } init(_ key: Key<Value>) { self.key = key self.observation = Defaults.observe(key, options: [.prior]) { [weak self] change in guard change.isPrior else { return } DispatchQueue.mainSafeAsync { self?.objectWillChange.send() } } } /// Reset the key back to its default value. func reset() { key.reset() } } } extension Defaults { /** Creates a SwiftUI `Toggle` view that is connected to a Bool `Defaults` key. ``` struct ShowAllDayEventsSetting: View { var body: some View { Defaults.Toggle("Show All-Day Events", key: .showAllDayEvents) } } ``` */ struct Toggle<Label, Key>: View where Label: View, Key: Defaults.Key<Bool> { // TODO: Find a way to store the handler without using an embedded class. private final class OnChangeHolder { var onChange: ((Bool) -> Void)? } private let label: () -> Label @ObservedObject private var observable: Defaults.Observable<Bool> private let onChangeHolder = OnChangeHolder() init(key: Key, @ViewBuilder label: @escaping () -> Label) { self.label = label self.observable = Defaults.Observable(key) } var body: some View { SwiftUI.Toggle(isOn: $observable.value, label: label) .onChange(of: observable.value) { onChangeHolder.onChange?($0) } } } } extension Defaults.Toggle where Label == Text { init<S>(_ title: S, key: Defaults.Key<Bool>) where S: StringProtocol { self.label = { Text(title) } self.observable = Defaults.Observable(key) } } extension Defaults.Toggle { /// Do something when the value changes to a different value. func onChange(_ action: @escaping (Bool) -> Void) -> Self { onChangeHolder.onChange = action return self } } struct NativeTextField: NSViewRepresentable { typealias NSViewType = InternalTextField @Binding var text: String var placeholder: String? var font: NSFont? var isFirstResponder = false @Binding var isFocused: Bool // Note: This is only readable. var isSingleLine = true final class InternalTextField: NSTextField { private var eventMonitor: LocalEventMonitor? var parent: NativeTextField init(_ parent: NativeTextField) { self.parent = parent super.init(frame: .zero) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func becomeFirstResponder() -> Bool { parent.isFocused = true // Cannot be `.leftMouseUp` as the color wheel swallows it. eventMonitor = LocalEventMonitor(events: [.leftMouseDown, .rightMouseDown, .keyDown]) { [weak self] event in guard let self = self else { return nil } if event.type == .keyDown { if event.keyCode == kVK_Escape { return nil } return event } let clickPoint = self.convert(event.locationInWindow, from: nil) let clickMargin: CGFloat = 3 if !self.frame.insetBy(dx: -clickMargin, dy: -clickMargin).contains(clickPoint) { self.blur() return nil } return event }.start() return super.becomeFirstResponder() } } final class Coordinator: NSObject, NSTextFieldDelegate { var parent: NativeTextField var didBecomeFirstResponder = false init(_ autoFocusTextField: NativeTextField) { self.parent = autoFocusTextField } func controlTextDidChange(_ notification: Notification) { parent.text = (notification.object as? NSTextField)?.stringValue ?? "" } func controlTextDidEndEditing(_ notification: Notification) { parent.isFocused = false } // This ensures the app doesn't close when pressing `Esc` (closing is the default behavior for `NSPanel`. func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { if commandSelector == #selector(NSResponder.cancelOperation(_:)) { parent.text = "" return true } return false } } func makeCoordinator() -> Coordinator { Coordinator(self) } func makeNSView(context: Context) -> NSViewType { let nsView = NSViewType(self) nsView.delegate = context.coordinator // This makes it scroll horizontally when text overflows instead of moving to a new line. if isSingleLine { nsView.cell?.usesSingleLineMode = true nsView.cell?.wraps = false nsView.cell?.isScrollable = true nsView.maximumNumberOfLines = 1 } return nsView } func updateNSView(_ nsView: NSViewType, context: Context) { nsView.bezelStyle = .roundedBezel nsView.stringValue = text nsView.placeholderString = placeholder if let font = font { nsView.font = font } // Note: Does not work without the dispatch call. DispatchQueue.main.async { if isFirstResponder, !context.coordinator.didBecomeFirstResponder, let window = nsView.window, window.firstResponder != nsView { window.makeFirstResponder(nsView) context.coordinator.didBecomeFirstResponder = true } } } } extension NSColorPanel { /// Show the color sampler. func showColorSampler() { // "_magnify:" let selector = String(":yfingam_".reversed()) perform(NSSelectorFromString(selector)) } } extension NSColorPanel { /** Publishes when the color in the color panel changes. */ var colorDidChangePublisher: AnyPublisher<Void, Never> { NotificationCenter.default .publisher(for: Self.colorDidChangeNotification, object: self) .map { _ in } .eraseToAnyPublisher() } } extension NSAlert { /// Show an alert as a window-modal sheet, or as an app-modal (window-indepedendent) alert if the window is `nil` or not given. @discardableResult static func showModal( for window: NSWindow? = nil, title: String, message: String? = nil, style: Style = .warning, buttonTitles: [String] = [], defaultButtonIndex: Int? = nil ) -> NSApplication.ModalResponse { NSAlert( title: title, message: message, style: style, buttonTitles: buttonTitles, defaultButtonIndex: defaultButtonIndex ) .runModal(for: window) } /// The index in the `buttonTitles` array for the button to use as default. /// Set `-1` to not have any default. Useful for really destructive actions. var defaultButtonIndex: Int { get { buttons.firstIndex { $0.keyEquivalent == "\r" } ?? -1 } set { // Clear the default button indicator from other buttons. for button in buttons where button.keyEquivalent == "\r" { button.keyEquivalent = "" } if newValue != -1 { buttons[newValue].keyEquivalent = "\r" } } } convenience init( title: String, message: String? = nil, style: Style = .warning, buttonTitles: [String] = [], defaultButtonIndex: Int? = nil ) { self.init() self.messageText = title self.alertStyle = style if let message = message { self.informativeText = message } addButtons(withTitles: buttonTitles) if let defaultButtonIndex = defaultButtonIndex { self.defaultButtonIndex = defaultButtonIndex } } /// Runs the alert as a window-modal sheet, or as an app-modal (window-indepedendent) alert if the window is `nil` or not given. @discardableResult func runModal(for window: NSWindow? = nil) -> NSApplication.ModalResponse { guard let window = window else { return runModal() } beginSheetModal(for: window) { returnCode in NSApp.stopModal(withCode: returnCode) } return NSApp.runModal(for: window) } /// Adds buttons with the given titles to the alert. func addButtons(withTitles buttonTitles: [String]) { for buttonTitle in buttonTitles { addButton(withTitle: buttonTitle) } } } extension View { func onNotification( /// Make the view subscribe to the given notification. _ name: Notification.Name, object: AnyObject? = nil, perform action: @escaping (Notification) -> Void ) -> some View { onReceive(NotificationCenter.default.publisher(for: name, object: object)) { action($0) } } } private var controlActionClosureProtocolAssociatedObjectKey: UInt8 = 0 protocol ControlActionClosureProtocol: NSObjectProtocol { var target: AnyObject? { get set } var action: Selector? { get set } } private final class ActionTrampoline<T>: NSObject { let action: (T) -> Void init(action: @escaping (T) -> Void) { self.action = action } @objc func action(sender: AnyObject) { // This is safe as it can only be `T`. // swiftlint:disable:next force_cast action(sender as! T) } } extension ControlActionClosureProtocol { /** Closure version of `.action` ``` let button = NSButton(title: "Unicorn", target: nil, action: nil) button.onAction { sender in print("Button action: \(sender)") } ``` */ func onAction(_ action: @escaping (Self) -> Void) { let trampoline = ActionTrampoline(action: action) target = trampoline self.action = #selector(ActionTrampoline<Self>.action(sender:)) objc_setAssociatedObject(self, &controlActionClosureProtocolAssociatedObjectKey, trampoline, .OBJC_ASSOCIATION_RETAIN) } } extension NSControl: ControlActionClosureProtocol {} extension NSMenuItem: ControlActionClosureProtocol {} extension NSWindow { func toggle() { if isVisible, isKeyWindow { performClose(nil) } else { if NSApp.activationPolicy() == .accessory { NSApp.activate(ignoringOtherApps: true) } makeKeyAndOrderFront(nil) } } } final class CallbackMenuItem: NSMenuItem { private static var validateCallback: ((NSMenuItem) -> Bool)? static func validate(_ callback: @escaping (NSMenuItem) -> Bool) { validateCallback = callback } init( _ title: String, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isHidden: Bool = false, callback: @escaping (NSMenuItem) -> Void ) { self.callback = callback super.init(title: title, action: #selector(action(_:)), keyEquivalent: key) self.target = self self.isEnabled = isEnabled self.isHidden = isHidden if let keyModifiers = keyModifiers { self.keyEquivalentModifierMask = keyModifiers } } @available(*, unavailable) required init(coder decoder: NSCoder) { fatalError() // swiftlint:disable:this fatal_error_message } private let callback: (NSMenuItem) -> Void @objc func action(_ sender: NSMenuItem) { callback(sender) } } extension CallbackMenuItem: NSMenuItemValidation { func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { Self.validateCallback?(menuItem) ?? true } } extension NSMenu { @discardableResult func addCallbackItem( _ title: String, key: String = "", keyModifiers: NSEvent.ModifierFlags? = nil, data: Any? = nil, isEnabled: Bool = true, isChecked: Bool = false, isHidden: Bool = false, callback: @escaping (NSMenuItem) -> Void ) -> NSMenuItem { let menuItem = CallbackMenuItem( title, key: key, keyModifiers: keyModifiers, data: data, isEnabled: isEnabled, isHidden: isHidden, callback: callback ) addItem(menuItem) return menuItem } @discardableResult func addSettingsItem() -> NSMenuItem { addCallbackItem("Preferences…", key: ",") { _ in SSApp.showSettingsWindow() } } @discardableResult func addQuitItem() -> NSMenuItem { addSeparator() return addCallbackItem("Quit \(SSApp.name)", key: "q") { _ in SSApp.quit() } } func addSeparator() { addItem(.separator()) } } private struct RespectDisabledViewModifier: ViewModifier { @Environment(\.isEnabled) private var isEnabled func body(content: Content) -> some View { content.opacity(isEnabled ? 1 : 0.5) } } extension Text { /// Make some text respect the current view environment being disabled. /// Useful for `Text` label to a control. func respectDisabled() -> some View { modifier(RespectDisabledViewModifier()) } } /// Convenience for opening URLs. extension URL { func open() { NSWorkspace.shared.open(self) } } extension String { /* ``` "https://sindresorhus.com".openUrl() ``` */ func openUrl() { URL(string: self)?.open() } } extension URL: ExpressibleByStringLiteral { /** Example: ``` let url: URL = "https://sindresorhus.com" ``` */ public init(stringLiteral value: StaticString) { self.init(string: "\(value)")! } } extension URL { /** Example: ``` URL("https://sindresorhus.com") ``` */ init(_ staticString: StaticString) { self.init(string: "\(staticString)")! } } private struct WindowAccessor: NSViewRepresentable { private final class WindowAccessorView: NSView { @Binding var windowBinding: NSWindow? init(binding: Binding<NSWindow?>) { self._windowBinding = binding super.init(frame: .zero) } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() windowBinding = window } @available(*, unavailable) required init?(coder: NSCoder) { fatalError() // swiftlint:disable:this fatal_error_message } } @Binding var window: NSWindow? init(_ window: Binding<NSWindow?>) { self._window = window } func makeNSView(context: Context) -> NSView { WindowAccessorView(binding: $window) } func updateNSView(_ nsView: NSView, context: Context) {} } extension View { /// Bind the native backing-window of a SwiftUI window to a property. func bindNativeWindow(_ window: Binding<NSWindow?>) -> some View { background(WindowAccessor(window)) } } private struct WindowViewModifier: ViewModifier { @State private var window: NSWindow? let onWindow: (NSWindow?) -> Void func body(content: Content) -> some View { onWindow(window) return content .bindNativeWindow($window) } } extension View { /// Access the native backing-window of a SwiftUI window. func accessNativeWindow(_ onWindow: @escaping (NSWindow?) -> Void) -> some View { modifier(WindowViewModifier(onWindow: onWindow)) } /// Set the window level of a SwiftUI window. func windowLevel(_ level: NSWindow.Level) -> some View { accessNativeWindow { $0?.level = level } } } extension NSView { /// Get a subview matching a condition. func firstSubview(deep: Bool = false, where matches: (NSView) -> Bool) -> NSView? { for subview in subviews { if matches(subview) { return subview } if deep, let match = subview.firstSubview(deep: deep, where: matches) { return match } } return nil } } extension NSObject { // Note: It's intentionally a getter to get the dynamic self. /// Returns the class name without module name. static var simpleClassName: String { String(describing: self) } /// Returns the class name of the instance without module name. var simpleClassName: String { Self.simpleClassName } } enum SSPublishers { /// Publishes when the app becomes active/inactive. static var appIsActive: AnyPublisher<Bool, Never> { Publishers.Merge( NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification) .map { _ in true }, NotificationCenter.default.publisher(for: NSApplication.didResignActiveNotification) .map { _ in false } ) .eraseToAnyPublisher() } } private struct AppearOnScreenView: NSViewControllerRepresentable { final class ViewController: NSViewController { var onViewDidAppear: (() -> Void)? var onViewDidDisappear: (() -> Void)? init() { super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("Not implemented") } override func loadView() { view = NSView() } override func viewDidAppear() { onViewDidAppear?() } override func viewDidDisappear() { onViewDidDisappear?() } } var onViewDidAppear: (() -> Void)? var onViewDidDisappear: (() -> Void)? func makeNSViewController(context: Context) -> ViewController { let viewController = ViewController() viewController.onViewDidAppear = onViewDidAppear viewController.onViewDidDisappear = onViewDidDisappear return viewController } func updateNSViewController(_ controller: ViewController, context: Context) {} } extension View { /** Called each time the view appears on screen. This is different from `.onAppear` which is only called when the view appears in the SwiftUI view hierarchy. */ func onAppearOnScreen(_ perform: @escaping () -> Void) -> some View { background(AppearOnScreenView(onViewDidAppear: perform)) } /** Called each time the view disappears from screen. This is different from `.onDisappear` which is only called when the view disappears from the SwiftUI view hierarchy. */ func onDisappearFromScreen(_ perform: @escaping () -> Void) -> some View { background(AppearOnScreenView(onViewDidDisappear: perform)) } } extension NSPasteboard { /// Returns a publisher that emits when the pasteboard changes. var simplePublisher: AnyPublisher<Void, Never> { Timer.publish(every: 0.2, tolerance: 0.1, on: .main, in: .common) .autoconnect() .prepend([]) // We want the publisher to also emit immediately when someone subscribes. .compactMap { [weak self] _ in self?.changeCount } .removeDuplicates() .map { _ in } .eraseToAnyPublisher() } } extension NSPasteboard { /// An observable object that publishes updates when the given pasteboard changes. final class SimpleObservable: ObservableObject { private var cancellables = Set<AnyCancellable>() private var pasteboardPublisherCancellable: AnyCancellable? private let onlyWhenAppIsActive: Bool @Published var pasteboard: NSPasteboard { didSet { if onlyWhenAppIsActive, !NSApp.isActive { stop() return } start() } } /** It starts listening to changes automatically, as long as `onlyWhenAppIsActive` is not `true`. - Parameters: - pasteboard: The pasteboard to listen to changes. - onlyWhenAppIsActive: Only listen to changes while the app is active. */ init(_ pasteboard: NSPasteboard, onlyWhileAppIsActive: Bool = false) { self.pasteboard = pasteboard self.onlyWhenAppIsActive = onlyWhileAppIsActive if onlyWhileAppIsActive { SSPublishers.appIsActive .sink { [weak self] isActive in guard let self = self else { return } if isActive { self.start() } else { self.stop() } } .store(in: &cancellables) if NSApp.isActive { start() } } else { start() } } @discardableResult func start() -> Self { pasteboardPublisherCancellable = pasteboard.simplePublisher.sink { [weak self] in self?.objectWillChange.send() } return self } @discardableResult func stop() -> Self { pasteboardPublisherCancellable = nil return self } } }
23.232086
151
0.689058
1afa5ff6773bae3b2ece8e2e1c64d8a7bda917d8
75
public enum LoadDirection: Hashable { case forward case backward }
15
37
0.72
90300ea0c9232c1ed8e8125473c4555eabadfa10
2,164
// // AppDelegate.swift // TipCal // // Created by Patil, Vijeth on 3/6/17. // Copyright © 2017 mobile. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
47.043478
285
0.754621
ebec67ffed6282b46cdec43cc6393d58e5f42120
4,026
// // NAError.swift // IBM Notifier // // Created by Simone Martorelli on 7/13/20. // Copyright © 2020 IBM Inc. All rights reserved // SPDX-License-Identifier: Apache2.0 // import Foundation enum NAError { case dataFormat(type: Enums.ModelError) case deepLinkHandling(type: Enums.DeepLinkHandlingError) case efclController(type: Enums.EFCLControllerError) class Enums { } } extension NAError: LocalizedError { var errorDescription: String? { switch self { case .dataFormat(let type): return type.localizedDescription case .deepLinkHandling(let type): return type.localizedDescription case .efclController(let type): return type.localizedDescription } } var efclExitReason: EFCLController.ExitReason { switch self { case .efclController(let type): return type.efclExitReason default: return .internalError } } } // MARK: - Model Errors extension NAError.Enums { enum ModelError { case noTypeDefined case noInfoToShow case noButtonDefined case noHelpButtonAllowedInNotification case invalidJSONPayload case invalidJSONFilepath case invalidJSONDecoding(errorDescription: String) } } extension NAError.Enums.ModelError: LocalizedError { var errorDescription: String? { switch self { case .noTypeDefined: return "No notification \"type\" parameter defined" case .noInfoToShow: return "No info to show for the desired UI type. Please check the documentation and make sure to define all the mandatory field for the desired UI type." case .noButtonDefined: return "No button defined" case .noHelpButtonAllowedInNotification: return "It's not allowed to define an help button in a \"banner\" UI type style." case .invalidJSONPayload: return "Invalid JSON payload." case .invalidJSONFilepath: return "Invalid JSON file path." case .invalidJSONDecoding(let errorDescription): return "Invalid JSON format: \(errorDescription)" } } } // MARK: - DeepLinkEngine Errors extension NAError.Enums { enum DeepLinkHandlingError { case failedToGetComponents case unsupportedPath case noParametersFound case invalidToken } } extension NAError.Enums.DeepLinkHandlingError: LocalizedError { var errorDescription: String? { switch self { case .failedToGetComponents: return "Failed to get URL's components" case .unsupportedPath: return "URL's path is not supported" case .noParametersFound: return "Failed to get URL's parameters" case .invalidToken: return "Unauthorized request" } } } // MARK: - Execution From Command Line Controller Errors extension NAError.Enums { enum EFCLControllerError { case invalidArgumentsSyntax case invalidArgumentsFormat case errorBuildingNotificationObject(description: String) } } extension NAError.Enums.EFCLControllerError: LocalizedError { var errorDescription: String? { switch self { case .invalidArgumentsSyntax: return "Invalid arguments syntax." case .invalidArgumentsFormat: return String(format: "Invalid argument syntax.") case .errorBuildingNotificationObject(let description): return String(format: "Error while trying to create notification object from arguments: %@.", description) } } var efclExitReason: EFCLController.ExitReason { switch self { case .invalidArgumentsSyntax: return .invalidArgumentsSyntax case .invalidArgumentsFormat: return .invalidArgumentFormat case .errorBuildingNotificationObject: return .invalidArgumentFormat } } }
30.044776
165
0.657228
642a8e05b1aad00d1e6f6dad7eaa91708eaaed5d
2,397
// // Entities.swift // WebSocketChat // // Created by k1x on 24/09/16. // Copyright © 2016 k1x. All rights reserved. // import Foundation import Gloss var dateFormatterVar : DateFormatter { let dateFormatter = DateFormatter(); dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; dateFormatter.timeZone = TimeZone(abbreviation: "UTC"); return dateFormatter; }; var dateFormatter = dateFormatterVar; enum CommandData { case Date(date : Date); case LatLng(lat : Float, lng : Float); case Complete(variants : [String]); case Rate(minMax : [Int32]); case Message(message : String); } struct Command : Decodable { var author : String?; var commandData : CommandData?; var selectedIndex : Int32?; var boolValue : Bool?; init() { } init?(json: JSON) { author = "author" <~~ json; if let message : String = "message" <~~ json { commandData = .Message(message : message); } else if let command : JSON = "command" <~~ json { let commandType : String! = "type" <~~ command; switch commandType { case "complete": if let variants : [String] = "data" <~~ command { commandData = .Complete(variants: variants); } break; case "date": if let date : String = "data" <~~ command { if let nsdate = dateFormatter.date(from: date) { commandData = .Date(date: nsdate); } } break; case "map": if let variants : JSON = "data" <~~ command { let lat : Float32! = "lat" <~~ variants; let lng : Float32! = "lng" <~~ variants; if lat != nil && lng != nil { commandData = .LatLng(lat : lat!, lng : lng!); } } break; case "rate": if let variants : [Int32] = "data" <~~ command { commandData = .Rate(minMax: variants); } break; default: break; } } } }
29.9625
74
0.457655
5671497e7b4e4092f755e52e409cb645d4ce82ae
5,066
// // MeteorOAuthViewController.swift // MeteorDDP // // Created by engrahsanali on 2020/04/17. // Copyright (c) 2020 engrahsanali. All rights reserved. // /* Copyright (c) 2020 Muhammad Ahsan Ali, AA-Creations 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 WebKit // MARK:- 🚀 MeteorOAuth - // TODO: Handle login failure > specific actions for cancellation, for example // TODO: Gotchas: connecting over wss, but registered domain is http... // TODO: Activity indicator? // TODO: Add redirect not popup; register as web app when setting up services to instructions // TODO: Login first with stored token // TODO: Tests // MARK:- 🚀 MeteorOAuth - View Controller to login meteor from third-party services public class MeteorOAuthViewController: UIViewController { // App must be set to redirect, rather than popup // https://github.com/meteor/meteor/wiki/OAuth-for-mobile-Meteor-clients#popup-versus-redirect-flow var meteor: MeteorClient? public var navigationBar: UINavigationBar! public var cancelButton: UIBarButtonItem! public var webView: WKWebView! public var url: URL! public var serviceName: String? override public func viewDidLoad() { navigationBar = UINavigationBar() // Offset by 20 pixels vertically to take the status bar into account let navigationItem = UINavigationItem() navigationItem.title = "Login" if let name = serviceName { navigationItem.title = "Login with \(name)" } cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(close)) navigationItem.rightBarButtonItem = cancelButton navigationBar!.items = [navigationItem] // Configure WebView let request = URLRequest(url: url) webView = WKWebView() webView.navigationDelegate = self webView.load(request) self.view.addSubview(webView) self.view.addSubview(navigationBar) } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() navigationBar.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 64) webView.frame = CGRect(x: 0, y: 64, width: self.view.frame.size.width, height: self.view.frame.size.height - 64) } @objc func close() { self.dismiss(animated: true, completion: nil) } func signIn(token: String, secret: String) { let params = ["oauth":["credentialToken": token, "credentialSecret": secret]] as MeteorKeyValue meteor?.loginUser(params: params, method: .login) { result, error in logger.log(.login, "Meteor login attempt \(String(describing: result)), \(String(describing: error))", .normal) self.close() } } } // MARK:- WKNavigationDelegate Methods extension MeteorOAuthViewController: WKNavigationDelegate { /* Start the network activity indicator when the web view is loading */ public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation) { UIApplication.shared.isNetworkActivityIndicatorVisible = true } /* Stop the network activity indicator when the loading finishes */ public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation) { UIApplication.shared.isNetworkActivityIndicatorVisible = false webView.evaluateJavaScript("JSON.parse(document.getElementById('config').innerHTML)") { (html, error) in if let json = html as? MeteorKeyValue { if let secret = json["credentialSecret"] as? String, let token = json["credentialToken"] as? String { webView.stopLoading() self.signIn(token: token, secret: secret) } } else { logger.logError(.error, "There was no json here") } } } }
38.969231
131
0.678839
4b23ccfe1d04ad2b0df0a3eb91402d68f76423ca
1,820
// // BoomEnum.swift // BoomMenuButton // // Created by Nightonke on 2017/4/26. // Copyright © 2017 Nightonke. All rights reserved. // /// The trace of position animations of boom-buttons when booming or rebooming. /// /// - straightLine: Boom-buttons boom in a straight line. /// - parabola1: Boom-buttons boom in a parabola line that opens downward. /// - parabola2: Boom-buttons boom in a parabola line that opens upward. /// - parabola3: Boom-buttons boom in a parabola line that opens rightward. /// - parabola4: Boom-buttons boom in a parabola line that opens leftward. /// - horizontalThrow1: Boom-buttons boom in a horizontal-throw line that opens downward. /// - horizontalThrow2: Boom-buttons boom in a horizontal-throw line that opens upward. /// - random: Boom-buttons boom in a random line selected from straight, parabola1, parabola2, parabola3, parabola4, horizonal-throw1 and horizonal-throw2 lines. public enum BoomEnum: Int { /// Boom-buttons boom in a straight line. case straightLine = 0 /// Boom-buttons boom in a parabola line that opens downward. case parabola1 /// Boom-buttons boom in a parabola line that opens upward. case parabola2 /// Boom-buttons boom in a parabola line that opens rightward. case parabola3 /// Boom-buttons boom in a parabola line that opens leftward. case parabola4 /// Boom-buttons boom in a horizontal-throw line that opens downward. case horizontalThrow1 /// Boom-buttons boom in a horizontal-throw line that opens upward. case horizontalThrow2 /// Boom-buttons boom in a random line selected from straight, parabola1, parabola2, parabola3, parabola4, horizonal-throw1 and horizonal-throw2 lines. case random static var count: Int { return BoomEnum.random.rawValue + 1 } }
43.333333
161
0.724176
9be1c4b688d4a9061f0c6400c7c2b32c13e15481
66,274
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public typealias unichar = UInt16 extension unichar { public init(unicodeScalarLiteral scalar: UnicodeScalar) { self.init(scalar.value) } } /// Returns a localized string, using the main bundle if one is not specified. public func NSLocalizedString(_ key: String, tableName: String? = nil, bundle: Bundle = Bundle.main, value: String = "", comment: String) -> String { return bundle.localizedString(forKey: key, value: value, table: tableName) } #if os(macOS) || os(iOS) internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue internal let kCFStringGraphemeCluster = CFStringCharacterClusterType.graphemeCluster internal let kCFStringComposedCharacterCluster = CFStringCharacterClusterType.composedCharacterCluster internal let kCFStringCursorMovementCluster = CFStringCharacterClusterType.cursorMovementCluster internal let kCFStringBackwardDeletionCluster = CFStringCharacterClusterType.backwardDeletionCluster internal let kCFStringNormalizationFormD = CFStringNormalizationForm.D internal let kCFStringNormalizationFormKD = CFStringNormalizationForm.KD internal let kCFStringNormalizationFormC = CFStringNormalizationForm.C internal let kCFStringNormalizationFormKC = CFStringNormalizationForm.KC #endif extension NSString { public struct EncodingConversionOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let allowLossy = EncodingConversionOptions(rawValue: 1) public static let externalRepresentation = EncodingConversionOptions(rawValue: 2) internal static let failOnPartialEncodingConversion = EncodingConversionOptions(rawValue: 1 << 20) } public struct EnumerationOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let byLines = EnumerationOptions(rawValue: 0) public static let byParagraphs = EnumerationOptions(rawValue: 1) public static let byComposedCharacterSequences = EnumerationOptions(rawValue: 2) public static let byWords = EnumerationOptions(rawValue: 3) public static let bySentences = EnumerationOptions(rawValue: 4) public static let reverse = EnumerationOptions(rawValue: 1 << 8) public static let substringNotRequired = EnumerationOptions(rawValue: 1 << 9) public static let localized = EnumerationOptions(rawValue: 1 << 10) internal static let forceFullTokens = EnumerationOptions(rawValue: 1 << 20) } } extension NSString { public struct CompareOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let caseInsensitive = CompareOptions(rawValue: 1) public static let literal = CompareOptions(rawValue: 2) public static let backwards = CompareOptions(rawValue: 4) public static let anchored = CompareOptions(rawValue: 8) public static let numeric = CompareOptions(rawValue: 64) public static let diacriticInsensitive = CompareOptions(rawValue: 128) public static let widthInsensitive = CompareOptions(rawValue: 256) public static let forcedOrdering = CompareOptions(rawValue: 512) public static let regularExpression = CompareOptions(rawValue: 1024) internal func _cfValue(_ fixLiteral: Bool = false) -> CFStringCompareFlags { #if os(macOS) || os(iOS) return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue: rawValue) : CFStringCompareFlags(rawValue: rawValue).union(.compareNonliteral) #else return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue) : CFStringCompareFlags(rawValue) | UInt(kCFCompareNonliteral) #endif } } } internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpression.Options) -> NSRegularExpression? { struct local { static let __NSRegularExpressionCache: NSCache<NSString, NSRegularExpression> = { let cache = NSCache<NSString, NSRegularExpression>() cache.name = "NSRegularExpressionCache" cache.countLimit = 10 return cache }() } let key = "\(options):\(pattern)" if let regex = local.__NSRegularExpressionCache.object(forKey: key._nsObject) { return regex } do { let regex = try NSRegularExpression(pattern: pattern, options: options) local.__NSRegularExpressionCache.setObject(regex, forKey: key._nsObject) return regex } catch { } return nil } internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? { let theRange = NSRange(location: 0, length: str.length) var cLength = 0 var used = 0 var options: NSString.EncodingConversionOptions = [] if externalRep { options.formUnion(.externalRepresentation) } if lossy { options.formUnion(.allowLossy) } if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) { if fatalOnError { fatalError("Conversion on encoding failed") } return nil } let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1) if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) { fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation") } buffer.advanced(by: cLength).initialize(to: 0) return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here } internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool { if ch > 0x0d && ch < 0x0085 { /* Quick test to cover most chars */ return false } return ch == 0x0a || ch == 0x0d || ch == 0x0085 || ch == 0x2028 || ch == 0x2029 } internal func isAParagraphSeparatorTypeCharacter(_ ch: unichar) -> Bool { if ch > 0x0d && ch < 0x2029 { /* Quick test to cover most chars */ return false } return ch == 0x0a || ch == 0x0d || ch == 0x2029 } open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID()) internal var _storage: String open var length: Int { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } return _storage.utf16.count } open func character(at index: Int) -> unichar { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } let start = _storage.utf16.startIndex return _storage.utf16[_storage.utf16.index(start, offsetBy: index)] } public override convenience init() { let characters = Array<unichar>(repeating: 0, count: 1) self.init(characters: characters, length: 0) } internal init(_ string: String) { _storage = string } public convenience required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.string") { let str = aDecoder._decodePropertyListForKey("NS.string") as! String self.init(string: str) } else { let decodedData : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") { guard let buffer = $0 else { return nil } return Data(buffer: buffer) } guard let data = decodedData else { return nil } self.init(data: data, encoding: String.Encoding.utf8.rawValue) } } public required convenience init(string aString: String) { self.init(aString) } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSString.self { return self } let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length) getCharacters(characters, range: NSRange(location: 0, length: length)) let result = NSString(characters: characters, length: length) characters.deinitialize(count: length) characters.deallocate() return result } open override func mutableCopy() -> Any { return mutableCopy(with: nil) } open func mutableCopy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSString.self || type(of: self) === NSMutableString.self { if let contents = _fastContents { return NSMutableString(characters: contents, length: length) } } let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length) getCharacters(characters, range: NSRange(location: 0, length: length)) let result = NSMutableString(characters: characters, length: length) characters.deinitialize(count: 1) characters.deallocate() return result } public static var supportsSecureCoding: Bool { return true } open func encode(with aCoder: NSCoder) { if let aKeyedCoder = aCoder as? NSKeyedArchiver { aKeyedCoder._encodePropertyList(self, forKey: "NS.string") } else { aCoder.encode(self) } } public init(characters: UnsafePointer<unichar>, length: Int) { _storage = String(decoding: UnsafeBufferPointer(start: characters, count: length), as: UTF16.self) } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { _storage = String(describing: value) } public convenience init?(cString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) { guard let str = CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding)) else { return nil } self.init(string: str._swiftObject) } internal func _fastCStringContents(_ nullTerminated: Bool) -> UnsafePointer<Int8>? { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if _storage._guts._isContiguousASCII { return unsafeBitCast(_storage._core.startASCII, to: UnsafePointer<Int8>.self) } } return nil } internal var _fastContents: UnsafePointer<UniChar>? { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if _storage._guts._isContiguousUTF16 { return UnsafePointer<UniChar>(_storage._core.startUTF16) } } return nil } internal var _encodingCantBeStoredInEightBitCFString: Bool { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return !_storage._guts._isContiguousASCII } return false } override open var _cfTypeID: CFTypeID { return CFStringGetTypeID() } open override func isEqual(_ object: Any?) -> Bool { guard let string = (object as? NSString)?._swiftObject else { return false } return self.isEqual(to: string) } open override var description: String { return _swiftObject } open override var hash: Int { return Int(bitPattern:CFStringHashNSString(self._cfObject)) } } extension NSString { public func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) { for idx in 0..<range.length { buffer[idx] = character(at: idx + range.location) } } public func substring(from: Int) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return String(_storage.utf16.suffix(from: _storage.utf16.index(_storage.utf16.startIndex, offsetBy: from)))! } else { return substring(with: NSRange(location: from, length: length - from)) } } public func substring(to: Int) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return String(_storage.utf16.prefix(upTo: _storage.utf16.index(_storage.utf16.startIndex, offsetBy: to)))! } else { return substring(with: NSRange(location: 0, length: to)) } } public func substring(with range: NSRange) -> String { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { let start = _storage.utf16.startIndex let min = _storage.utf16.index(start, offsetBy: range.location) let max = _storage.utf16.index(start, offsetBy: range.location + range.length) return String(decoding: _storage.utf16[min..<max], as: UTF16.self) } else { let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length) getCharacters(buff, range: range) let result = String(describing: buff) buff.deinitialize(count: 1) buff.deallocate() return result } } public func compare(_ string: String) -> ComparisonResult { return compare(string, options: [], range: NSRange(location: 0, length: length)) } public func compare(_ string: String, options mask: CompareOptions) -> ComparisonResult { return compare(string, options: mask, range: NSRange(location: 0, length: length)) } public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange) -> ComparisonResult { return compare(string, options: mask, range: compareRange, locale: nil) } public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: Any?) -> ComparisonResult { var res: CFComparisonResult if let loc = locale { res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject) } else { res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), nil) } return ComparisonResult._fromCF(res) } public func caseInsensitiveCompare(_ string: String) -> ComparisonResult { return compare(string, options: .caseInsensitive, range: NSRange(location: 0, length: length)) } public func localizedCompare(_ string: String) -> ComparisonResult { return compare(string, options: [], range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC()) } public func localizedCaseInsensitiveCompare(_ string: String) -> ComparisonResult { return compare(string, options: .caseInsensitive, range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC()) } public func localizedStandardCompare(_ string: String) -> ComparisonResult { return compare(string, options: [.caseInsensitive, .numeric, .widthInsensitive, .forcedOrdering], range: NSRange(location: 0, length: length), locale: Locale.current._bridgeToObjectiveC()) } public func isEqual(to aString: String) -> Bool { if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { return _storage == aString } else { return length == aString.length && compare(aString, options: .literal, range: NSRange(location: 0, length: length)) == .orderedSame } } public func hasPrefix(_ str: String) -> Bool { return range(of: str, options: .anchored, range: NSRange(location: 0, length: length)).location != NSNotFound } public func hasSuffix(_ str: String) -> Bool { return range(of: str, options: [.anchored, .backwards], range: NSRange(location: 0, length: length)).location != NSNotFound } public func commonPrefix(with str: String, options mask: CompareOptions = []) -> String { var currentSubstring: CFMutableString? let isLiteral = mask.contains(.literal) var lastMatch = NSRange() let selfLen = length let otherLen = str.length var low = 0 var high = selfLen var probe = (low + high) / 2 if (probe > otherLen) { probe = otherLen // A little heuristic to avoid some extra work } if selfLen == 0 || otherLen == 0 { return "" } var numCharsBuffered = 0 var arrayBuffer = [unichar](repeating: 0, count: 100) let other = str._nsObject return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer<unichar>(mutating: _fastContents)) { (selfChars: UnsafeMutablePointer<unichar>) -> String in // Now do the binary search. Note that the probe value determines the length of the substring to check. while true { let range = NSRange(location: 0, length: isLiteral ? probe + 1 : NSMaxRange(rangeOfComposedCharacterSequence(at: probe))) // Extend the end of the composed char sequence if range.length > numCharsBuffered { // Buffer more characters if needed getCharacters(selfChars, range: NSRange(location: numCharsBuffered, length: range.length - numCharsBuffered)) numCharsBuffered = range.length } if currentSubstring == nil { currentSubstring = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorSystemDefault, selfChars, range.length, range.length, kCFAllocatorNull) } else { CFStringSetExternalCharactersNoCopy(currentSubstring, selfChars, range.length, range.length) } if other.range(of: currentSubstring!._swiftObject, options: mask.union(.anchored), range: NSRange(location: 0, length: otherLen)).length != 0 { // Match lastMatch = range low = probe + 1 } else { high = probe } if low >= high { break } probe = (low + high) / 2 } return lastMatch.length != 0 ? substring(with: lastMatch) : "" } } public func contains(_ str: String) -> Bool { return range(of: str, options: [], range: NSRange(location: 0, length: length), locale: nil).location != NSNotFound } public func localizedCaseInsensitiveContains(_ str: String) -> Bool { return range(of: str, options: .caseInsensitive, range: NSRange(location: 0, length: length), locale: Locale.current).location != NSNotFound } public func localizedStandardContains(_ str: String) -> Bool { return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSRange(location: 0, length: length), locale: Locale.current).location != NSNotFound } public func localizedStandardRange(of str: String) -> NSRange { return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSRange(location: 0, length: length), locale: Locale.current) } public func range(of searchString: String) -> NSRange { return range(of: searchString, options: [], range: NSRange(location: 0, length: length), locale: nil) } public func range(of searchString: String, options mask: CompareOptions = []) -> NSRange { return range(of: searchString, options: mask, range: NSRange(location: 0, length: length), locale: nil) } public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange { return range(of: searchString, options: mask, range: searchRange, locale: nil) } internal func _rangeOfRegularExpressionPattern(regex pattern: String, options mask: CompareOptions, range searchRange: NSRange, locale: Locale?) -> NSRange { var matchedRange = NSRange(location: NSNotFound, length: 0) let regexOptions: NSRegularExpression.Options = mask.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSRegularExpression.MatchingOptions = mask.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { matchedRange = regex.rangeOfFirstMatch(in: _swiftObject, options: matchingOptions, range: searchRange) } return matchedRange } public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange, locale: Locale?) -> NSRange { let findStrLen = searchString.length let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)") if mask.contains(.regularExpression) { return _rangeOfRegularExpressionPattern(regex: searchString, options: mask, range:searchRange, locale: locale) } if searchRange.length == 0 || findStrLen == 0 { // ??? This last item can't be here for correct Unicode compares return NSRange(location: NSNotFound, length: 0) } var result = CFRange() let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in if let loc = locale { return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), loc._cfObject, rangep) } else { return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), nil, rangep) } } if res { return NSRange(location: result.location, length: result.length) } else { return NSRange(location: NSNotFound, length: 0) } } public func rangeOfCharacter(from searchSet: CharacterSet) -> NSRange { return rangeOfCharacter(from: searchSet, options: [], range: NSRange(location: 0, length: length)) } public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = []) -> NSRange { return rangeOfCharacter(from: searchSet, options: mask, range: NSRange(location: 0, length: length)) } public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange { let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)") var result = CFRange() let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in return CFStringFindCharacterFromSet(_cfObject, searchSet._cfObject, CFRange(searchRange), mask._cfValue(), rangep) } if res { return NSRange(location: result.location, length: result.length) } else { return NSRange(location: NSNotFound, length: 0) } } public func rangeOfComposedCharacterSequence(at index: Int) -> NSRange { let range = CFStringGetRangeOfCharacterClusterAtIndex(_cfObject, index, kCFStringComposedCharacterCluster) return NSRange(location: range.location, length: range.length) } public func rangeOfComposedCharacterSequences(for range: NSRange) -> NSRange { let length = self.length var start: Int var end: Int if range.location == length { start = length } else { start = rangeOfComposedCharacterSequence(at: range.location).location } var endOfRange = NSMaxRange(range) if endOfRange == length { end = length } else { if range.length > 0 { endOfRange = endOfRange - 1 // We want 0-length range to be treated same as 1-length range. } end = NSMaxRange(rangeOfComposedCharacterSequence(at: endOfRange)) } return NSRange(location: start, length: end - start) } public func appending(_ aString: String) -> String { return _swiftObject + aString } public var doubleValue: Double { var start: Int = 0 var result = 0.0 let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Double) -> Void in result = value } return result } public var floatValue: Float { var start: Int = 0 var result: Float = 0.0 let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Float) -> Void in result = value } return result } public var intValue: Int32 { return Scanner(string: _swiftObject).scanInt32() ?? 0 } public var integerValue: Int { let scanner = Scanner(string: _swiftObject) var value: Int = 0 let _ = scanner.scanInt(&value) return value } public var longLongValue: Int64 { return Scanner(string: _swiftObject).scanInt64() ?? 0 } public var boolValue: Bool { let scanner = Scanner(string: _swiftObject) // skip initial whitespace if present let _ = scanner.scanCharactersFromSet(.whitespaces) // scan a single optional '+' or '-' character, followed by zeroes if scanner.scanString("+") == nil { let _ = scanner.scanString("-") } // scan any following zeroes let _ = scanner.scanCharactersFromSet(CharacterSet(charactersIn: "0")) return scanner.scanCharactersFromSet(CharacterSet(charactersIn: "tTyY123456789")) != nil } public var uppercased: String { return uppercased(with: nil) } public var lowercased: String { return lowercased(with: nil) } public var capitalized: String { return capitalized(with: nil) } public var localizedUppercase: String { return uppercased(with: Locale.current) } public var localizedLowercase: String { return lowercased(with: Locale.current) } public var localizedCapitalized: String { return capitalized(with: Locale.current) } public func uppercased(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringUppercase(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } public func lowercased(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringLowercase(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } public func capitalized(with locale: Locale?) -> String { let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)! CFStringCapitalize(mutableCopy, locale?._cfObject ?? nil) return mutableCopy._swiftObject } internal func _getBlockStart(_ startPtr: UnsafeMutablePointer<Int>?, end endPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, forRange range: NSRange, stopAtLineSeparators line: Bool) { let len = length var ch: unichar precondition(range.length <= len && range.location < len - range.length, "Range {\(range.location), \(range.length)} is out of bounds of length \(len)") if range.location == 0 && range.length == len && contentsEndPtr == nil { // This occurs often startPtr?.pointee = 0 endPtr?.pointee = range.length return } /* Find the starting point first */ if let startPtr = startPtr { var start: Int = 0 if range.location == 0 { start = 0 } else { var buf = _NSStringBuffer(string: self, start: range.location, end: len) /* Take care of the special case where start happens to fall right between \r and \n */ ch = buf.currentCharacter buf.rewind() if ch == 0x0a && buf.currentCharacter == 0x0d { buf.rewind() } while true { if line ? isALineSeparatorTypeCharacter(buf.currentCharacter) : isAParagraphSeparatorTypeCharacter(buf.currentCharacter) { start = buf.location + 1 break } else if buf.location <= 0 { start = 0 break } else { buf.rewind() } } startPtr.pointee = start } } if (endPtr != nil || contentsEndPtr != nil) { var endOfContents = 1 var lineSeparatorLength = 1 var buf = _NSStringBuffer(string: self, start: NSMaxRange(range) - (range.length > 0 ? 1 : 0), end: len) /* First look at the last char in the range (if the range is zero length, the char after the range) to see if we're already on or within a end of line sequence... */ ch = buf.currentCharacter if ch == 0x0a { endOfContents = buf.location buf.rewind() if buf.currentCharacter == 0x0d { lineSeparatorLength = 2 endOfContents -= 1 } } else { while true { if line ? isALineSeparatorTypeCharacter(ch) : isAParagraphSeparatorTypeCharacter(ch) { endOfContents = buf.location /* This is actually end of contentsRange */ buf.advance() /* OK for this to go past the end */ if ch == 0x0d && buf.currentCharacter == 0x0a { lineSeparatorLength = 2 } break } else if buf.location == len { endOfContents = len lineSeparatorLength = 0 break } else { buf.advance() ch = buf.currentCharacter } } } contentsEndPtr?.pointee = endOfContents endPtr?.pointee = endOfContents + lineSeparatorLength } } public func getLineStart(_ startPtr: UnsafeMutablePointer<Int>?, end lineEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) { _getBlockStart(startPtr, end: lineEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: true) } public func lineRange(for range: NSRange) -> NSRange { var start = 0 var lineEnd = 0 getLineStart(&start, end: &lineEnd, contentsEnd: nil, for: range) return NSRange(location: start, length: lineEnd - start) } public func getParagraphStart(_ startPtr: UnsafeMutablePointer<Int>?, end parEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) { _getBlockStart(startPtr, end: parEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: false) } public func paragraphRange(for range: NSRange) -> NSRange { var start = 0 var parEnd = 0 getParagraphStart(&start, end: &parEnd, contentsEnd: nil, for: range) return NSRange(location: start, length: parEnd - start) } public func enumerateSubstrings(in range: NSRange, options opts: EnumerationOptions = [], using block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) { NSUnimplemented() } public func enumerateLines(_ block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) { enumerateSubstrings(in: NSRange(location: 0, length: length), options:.byLines) { substr, substrRange, enclosingRange, stop in block(substr!, stop) } } public var utf8String: UnsafePointer<Int8>? { return _bytesInEncoding(self, .utf8, false, false, false) } public var fastestEncoding: UInt { return String.Encoding.unicode.rawValue } public var smallestEncoding: UInt { if canBeConverted(to: String.Encoding.ascii.rawValue) { return String.Encoding.ascii.rawValue } return String.Encoding.unicode.rawValue } public func data(using encoding: UInt, allowLossyConversion lossy: Bool = false) -> Data? { let len = length var reqSize = 0 let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) if !CFStringIsEncodingAvailable(cfStringEncoding) { return nil } let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, nil, 0, &reqSize) if convertedLen != len { return nil // Not able to do it all... } if 0 < reqSize { var data = Data(count: reqSize) data.count = data.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen { return reqSize } else { fatalError("didn't convert all characters") } } return data } return Data() } public func data(using encoding: UInt) -> Data? { return data(using: encoding, allowLossyConversion: false) } public func canBeConverted(to encoding: UInt) -> Bool { if encoding == String.Encoding.unicode.rawValue || encoding == String.Encoding.nonLossyASCII.rawValue || encoding == String.Encoding.utf8.rawValue { return true } return __CFStringEncodeByteStream(_cfObject, 0, length, false, CFStringConvertNSStringEncodingToEncoding(encoding), 0, nil, 0, nil) == length } public func cString(using encoding: UInt) -> UnsafePointer<Int8>? { return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false) } public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool { var used = 0 if type(of: self) == NSString.self || type(of: self) == NSMutableString.self { if _storage._guts._isContiguousASCII { used = min(self.length, maxBufferCount - 1) _storage._core.startASCII.withMemoryRebound(to: Int8.self, capacity: used) { buffer.moveAssign(from: $0, count: used) } buffer.advanced(by: used).initialize(to: 0) return true } } if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSRange(location: 0, length: self.length), remaining: nil) { buffer.advanced(by: used).initialize(to: 0) return true } return false } public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool { var totalBytesWritten = 0 var numCharsProcessed = 0 let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding) var result = true if length > 0 { if CFStringIsEncodingAvailable(cfStringEncoding) { let lossyOk = options.contains(.allowLossy) let externalRep = options.contains(.externalRepresentation) let failOnPartial = options.contains(.failOnPartialEncodingConversion) let bytePtr = buffer?.bindMemory(to: UInt8.self, capacity: maxBufferCount) numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, bytePtr, bytePtr != nil ? maxBufferCount : 0, &totalBytesWritten) if (failOnPartial && numCharsProcessed < range.length) || numCharsProcessed == 0 { result = false } } else { result = false /* ??? Need other encodings */ } } usedBufferCount?.pointee = totalBytesWritten leftover?.pointee = NSRange(location: range.location + numCharsProcessed, length: range.length - numCharsProcessed) return result } public func maximumLengthOfBytes(using enc: UInt) -> Int { let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc) let result = CFStringGetMaximumSizeForEncoding(length, cfEnc) return result == kCFNotFound ? 0 : result } public func lengthOfBytes(using enc: UInt) -> Int { let len = length var numBytes: CFIndex = 0 let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc) let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, false, cfEnc, 0, nil, 0, &numBytes) return convertedLen != len ? 0 : numBytes } open class var availableStringEncodings: UnsafePointer<UInt> { struct once { static let encodings: UnsafePointer<UInt> = { let cfEncodings = CFStringGetListOfAvailableEncodings()! var idx = 0 var numEncodings = 0 while cfEncodings.advanced(by: idx).pointee != kCFStringEncodingInvalidId { idx += 1 numEncodings += 1 } let theEncodingList = UnsafeMutablePointer<String.Encoding.RawValue>.allocate(capacity: numEncodings + 1) theEncodingList.advanced(by: numEncodings).pointee = 0 // Terminator numEncodings -= 1 while numEncodings >= 0 { theEncodingList.advanced(by: numEncodings).pointee = CFStringConvertEncodingToNSStringEncoding(cfEncodings.advanced(by: numEncodings).pointee) numEncodings -= 1 } return UnsafePointer<UInt>(theEncodingList) }() } return once.encodings } open class func localizedName(of encoding: UInt) -> String { if let theString = CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding)) { // TODO: read the localized version from the Foundation "bundle" return theString._swiftObject } return "" } open class var defaultCStringEncoding: UInt { return CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding()) } open var decomposedStringWithCanonicalMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormD) return string._swiftObject } open var precomposedStringWithCanonicalMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormC) return string._swiftObject } open var decomposedStringWithCompatibilityMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormKD) return string._swiftObject } open var precomposedStringWithCompatibilityMapping: String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringNormalize(string, kCFStringNormalizationFormKC) return string._swiftObject } open func components(separatedBy separator: String) -> [String] { let len = length var lrange = range(of: separator, options: [], range: NSRange(location: 0, length: len)) if lrange.length == 0 { return [_swiftObject] } else { var array = [String]() var srange = NSRange(location: 0, length: len) while true { let trange = NSRange(location: srange.location, length: lrange.location - srange.location) array.append(substring(with: trange)) srange.location = lrange.location + lrange.length srange.length = len - srange.location lrange = range(of: separator, options: [], range: srange) if lrange.length == 0 { break } } array.append(substring(with: srange)) return array } } open func components(separatedBy separator: CharacterSet) -> [String] { let len = length var range = rangeOfCharacter(from: separator, options: [], range: NSRange(location: 0, length: len)) if range.length == 0 { return [_swiftObject] } else { var array = [String]() var srange = NSRange(location: 0, length: len) while true { let trange = NSRange(location: srange.location, length: range.location - srange.location) array.append(substring(with: trange)) srange.location = range.location + range.length srange.length = len - srange.location range = rangeOfCharacter(from: separator, options: [], range: srange) if range.length == 0 { break } } array.append(substring(with: srange)) return array } } open func trimmingCharacters(in set: CharacterSet) -> String { let len = length var buf = _NSStringBuffer(string: self, start: 0, end: len) while !buf.isAtEnd, let character = UnicodeScalar(buf.currentCharacter), set.contains(character) { buf.advance() } let startOfNonTrimmedRange = buf.location // This points at the first char not in the set if startOfNonTrimmedRange == len { // Note that this also covers the len == 0 case, which is important to do here before the len-1 in the next line. return "" } else if startOfNonTrimmedRange < len - 1 { buf.location = len - 1 while let character = UnicodeScalar(buf.currentCharacter), set.contains(character), buf.location >= startOfNonTrimmedRange { buf.rewind() } let endOfNonTrimmedRange = buf.location return substring(with: NSRange(location: startOfNonTrimmedRange, length: endOfNonTrimmedRange + 1 - startOfNonTrimmedRange)) } else { return substring(with: NSRange(location: startOfNonTrimmedRange, length: 1)) } } open func padding(toLength newLength: Int, withPad padString: String, startingAt padIndex: Int) -> String { let len = length if newLength <= len { // The simple cases (truncation) return newLength == len ? _swiftObject : substring(with: NSRange(location: 0, length: newLength)) } let padLen = padString.length if padLen < 1 { fatalError("empty pad string") } if padIndex >= padLen { fatalError("out of range padIndex") } let mStr = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, _cfObject)! CFStringPad(mStr, padString._cfObject, newLength, padIndex) return mStr._swiftObject } open func folding(options: CompareOptions = [], locale: Locale?) -> String { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, self._cfObject) CFStringFold(string, options._cfValue(), locale?._cfObject) return string._swiftObject } internal func _stringByReplacingOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range: NSRange) -> String { let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSRegularExpression.MatchingOptions = options.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { return regex.stringByReplacingMatches(in: _swiftObject, options: matchingOptions, range: range, withTemplate: replacement) } return "" } open func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> String { if options.contains(.regularExpression) { return _stringByReplacingOccurrencesOfRegularExpressionPattern(target, withTemplate: replacement, options: options, range: searchRange) } let str = mutableCopy(with: nil) as! NSMutableString if str.replaceOccurrences(of: target, with: replacement, options: options, range: searchRange) == 0 { return _swiftObject } else { return str._swiftObject } } open func replacingOccurrences(of target: String, with replacement: String) -> String { return replacingOccurrences(of: target, with: replacement, options: [], range: NSRange(location: 0, length: length)) } open func replacingCharacters(in range: NSRange, with replacement: String) -> String { let str = mutableCopy(with: nil) as! NSMutableString str.replaceCharacters(in: range, with: replacement) return str._swiftObject } open func applyingTransform(_ transform: String, reverse: Bool) -> String? { let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)! CFStringReplaceAll(string, _cfObject) if (CFStringTransform(string, nil, transform._cfObject, reverse)) { return string._swiftObject } else { return nil } } internal func _getExternalRepresentation(_ data: inout Data, _ dest: URL, _ enc: UInt) throws { let length = self.length var numBytes = 0 let theRange = NSRange(location: 0, length: length) if !getBytes(nil, maxLength: Int.max - 1, usedLength: &numBytes, encoding: enc, options: [], range: theRange, remaining: nil) { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteInapplicableStringEncoding.rawValue, userInfo: [ NSURLErrorKey: dest, ]) } var mData = Data(count: numBytes) // The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?) var used = 0 // This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers. try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Void in if !getBytes(mutableBytes, maxLength: numBytes, usedLength: &used, encoding: enc, options: [], range: theRange, remaining: nil) { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [ NSURLErrorKey: dest, ]) } } data = mData } internal func _writeTo(_ url: URL, _ useAuxiliaryFile: Bool, _ enc: UInt) throws { var data = Data() try _getExternalRepresentation(&data, url, enc) try data.write(to: url, options: useAuxiliaryFile ? .atomic : []) } open func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { try _writeTo(url, useAuxiliaryFile, enc) } open func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws { try _writeTo(URL(fileURLWithPath: path), useAuxiliaryFile, enc) } public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { // ignore the no-copy-ness self.init(characters: characters, length: length) if freeBuffer { // cant take a hint here... free(UnsafeMutableRawPointer(characters)) } } public convenience init?(utf8String nullTerminatedCString: UnsafePointer<Int8>) { guard let str = String(validatingUTF8: nullTerminatedCString) else { return nil } self.init(str) } public convenience init(format: String, arguments argList: CVaListPointer) { let str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)! self.init(str._swiftObject) } public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) { let str: CFString if let loc = locale { if type(of: loc) === NSLocale.self || type(of: loc) === NSDictionary.self { str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, unsafeBitCast(loc, to: CFDictionary.self), format._cfObject, argList) } else { fatalError("locale parameter must be a NSLocale or a NSDictionary") } } else { str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList) } self.init(str._swiftObject) } public convenience init(format: NSString, _ args: CVarArg...) { let str = withVaList(args) { (vaPtr) -> CFString? in CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, vaPtr) }! self.init(str._swiftObject) } public convenience init?(data: Data, encoding: UInt) { if data.isEmpty { self.init("") } else { guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> CFString? in return CFStringCreateWithBytes(kCFAllocatorDefault, bytes, data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true) }) else { return nil } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { return nil } } } public convenience init?(bytes: UnsafeRawPointer, length len: Int, encoding: UInt) { let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: len) guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { return nil } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { return nil } } public convenience init?(bytesNoCopy bytes: UnsafeMutableRawPointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ { // just copy for now since the internal storage will be a copy anyhow self.init(bytes: bytes, length: len, encoding: encoding) if freeBuffer { // dont take the hint free(bytes) } } public convenience init(contentsOf url: URL, encoding enc: UInt) throws { let readResult = try NSData(contentsOf: url, options: []) let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity: readResult.length) guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to create a string using the specified encoding." ]) } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to bridge CFString to String." ]) } } public convenience init(contentsOfFile path: String, encoding enc: UInt) throws { try self.init(contentsOf: URL(fileURLWithPath: path), encoding: enc) } public convenience init(contentsOf url: URL, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws { let (readResult, urlResponse) = try NSData.contentsOf(url: url) let encoding: UInt let offset: Int // Look for a BOM (Byte Order Marker) to try and determine the text Encoding, this also skips // over the bytes. This takes precedence over the textEncoding in the http header let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity:readResult.length) if readResult.length >= 4 && bytePtr[0] == 0xFF && bytePtr[1] == 0xFE && bytePtr[2] == 0x00 && bytePtr[3] == 0x00 { encoding = String.Encoding.utf32LittleEndian.rawValue offset = 4 } else if readResult.length >= 2 && bytePtr[0] == 0xFE && bytePtr[1] == 0xFF { encoding = String.Encoding.utf16BigEndian.rawValue offset = 2 } else if readResult.length >= 2 && bytePtr[0] == 0xFF && bytePtr[1] == 0xFE { encoding = String.Encoding.utf16LittleEndian.rawValue offset = 2 } else if readResult.length >= 4 && bytePtr[0] == 0x00 && bytePtr[1] == 0x00 && bytePtr[2] == 0xFE && bytePtr[3] == 0xFF { encoding = String.Encoding.utf32BigEndian.rawValue offset = 4 } else if let charSet = urlResponse?.textEncodingName, let textEncoding = String.Encoding(charSet: charSet) { encoding = textEncoding.rawValue offset = 0 } else { //Need to work on more conditions. This should be the default encoding = String.Encoding.utf8.rawValue offset = 0 } // Since the encoding being passed includes the byte order the BOM wont be checked or skipped, so pass offset to // manually skip the BOM header. guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr + offset, readResult.length - offset, CFStringConvertNSStringEncodingToEncoding(encoding), true) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to create a string using the specified encoding." ]) } var str: String? if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) { self.init(str!) } else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [ "NSDebugDescription" : "Unable to bridge CFString to String." ]) } enc?.pointee = encoding } public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws { try self.init(contentsOf: URL(fileURLWithPath: path), usedEncoding: enc) } } extension NSString : ExpressibleByStringLiteral { } open class NSMutableString : NSString { open func replaceCharacters(in range: NSRange, with aString: String) { guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else { NSRequiresConcreteImplementation() } let start = _storage.utf16.startIndex let min = _storage.utf16.index(start, offsetBy: range.location).samePosition(in: _storage)! let max = _storage.utf16.index(start, offsetBy: range.location + range.length).samePosition(in: _storage)! _storage.replaceSubrange(min..<max, with: aString) } public required override init(characters: UnsafePointer<unichar>, length: Int) { super.init(characters: characters, length: length) } public required init(capacity: Int) { super.init(characters: [], length: 0) } public convenience required init?(coder aDecoder: NSCoder) { guard let str = NSString(coder: aDecoder) else { return nil } self.init(string: String._unconditionallyBridgeFromObjectiveC(str)) } public required convenience init(unicodeScalarLiteral value: StaticString) { self.init(stringLiteral: value) } public required convenience init(extendedGraphemeClusterLiteral value: StaticString) { self.init(stringLiteral: value) } public required init(stringLiteral value: StaticString) { super.init(value.description) } public required init(string aString: String) { super.init(aString) } internal func appendCharacters(_ characters: UnsafePointer<unichar>, length: Int) { let str = String(decoding: UnsafeBufferPointer(start: characters, count: length), as: UTF16.self) if type(of: self) == NSMutableString.self { _storage.append(str) } else { replaceCharacters(in: NSRange(location: self.length, length: 0), with: str) } } internal func _cfAppendCString(_ characters: UnsafePointer<Int8>, length: Int) { if type(of: self) == NSMutableString.self { _storage.append(String(cString: characters)) } } } extension NSMutableString { public func insert(_ aString: String, at loc: Int) { replaceCharacters(in: NSRange(location: loc, length: 0), with: aString) } public func deleteCharacters(in range: NSRange) { replaceCharacters(in: range, with: "") } public func append(_ aString: String) { replaceCharacters(in: NSRange(location: length, length: 0), with: aString) } public func setString(_ aString: String) { replaceCharacters(in: NSRange(location: 0, length: length), with: aString) } internal func _replaceOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range searchRange: NSRange) -> Int { let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : [] let matchingOptions: NSRegularExpression.MatchingOptions = options.contains(.anchored) ? .anchored : [] if let regex = _createRegexForPattern(pattern, regexOptions) { return regex.replaceMatches(in: self, options: matchingOptions, range: searchRange, withTemplate: replacement) } return 0 } public func replaceOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> Int { let backwards = options.contains(.backwards) let len = length precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Search range is out of bounds") if options.contains(.regularExpression) { return _replaceOccurrencesOfRegularExpressionPattern(target, withTemplate:replacement, options:options, range: searchRange) } if let findResults = CFStringCreateArrayWithFindResults(kCFAllocatorSystemDefault, _cfObject, target._cfObject, CFRange(searchRange), options._cfValue(true)) { let numOccurrences = CFArrayGetCount(findResults) for cnt in 0..<numOccurrences { let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1) replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement) } return numOccurrences } else { return 0 } } public func applyTransform(_ transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer?) -> Bool { var cfRange = CFRangeMake(range.location, range.length) return withUnsafeMutablePointer(to: &cfRange) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in if CFStringTransform(_cfMutableObject, rangep, transform._cfObject, reverse) { resultingRange?.pointee.location = rangep.pointee.location resultingRange?.pointee.length = rangep.pointee.length return true } return false } } } extension String { // this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters internal var length: Int { return utf16.count } } extension NSString : _CFBridgeable, _SwiftBridgeable { typealias SwiftType = String internal var _cfObject: CFString { return unsafeBitCast(self, to: CFString.self) } internal var _swiftObject: String { return String._unconditionallyBridgeFromObjectiveC(self) } } extension NSMutableString { internal var _cfMutableObject: CFMutableString { return unsafeBitCast(self, to: CFMutableString.self) } } extension CFString : _NSBridgeable, _SwiftBridgeable { typealias NSType = NSString typealias SwiftType = String internal var _nsObject: NSType { return unsafeBitCast(self, to: NSString.self) } internal var _swiftObject: String { return _nsObject._swiftObject } } extension String : _NSBridgeable, _CFBridgeable { typealias NSType = NSString typealias CFType = CFString internal var _nsObject: NSType { return _bridgeToObjectiveC() } internal var _cfObject: CFType { return _nsObject._cfObject } } extension NSString : _StructTypeBridgeable { public typealias _StructType = String public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } }
44.810007
274
0.642439
2964c7e7caa481871a4ae82ca6d85a2c71db2ac5
6,932
public enum EndpointCacheError: Swift.Error { case unexpctedResponseStatus(HTTPStatus, uri: URI) case contentDecodeFailure(Error) } /// Handles the complexities of HTTP caching. public final class EndpointCache<T> where T: Decodable { private var cached: T? private var request: EventLoopFuture<T>? private var headers: HTTPHeaders? private var cacheUntil: Date? private let sync: Lock private let uri: URI /// The designated initializer. /// - Parameters: /// - uri: The `URI` of the resource to be downloaded. public init(uri: URI) { self.uri = uri self.sync = .init() } /// Downloads the resource. /// - Parameters: /// - request: The `Request` which is initiating the download. /// - logger: An optional logger public func get(on request: Request, logger: Logger? = nil) -> EventLoopFuture<T> { return self.download(on: request.eventLoop, using: request.client, logger: logger ?? request.logger) } /// Downloads the resource. /// - Parameters: /// - eventLoop: The `EventLoop` to use for the download. /// - client: The `Client` which will perform the download. /// - logger: An optional logger public func get(using client: Client, logger: Logger? = nil, on eventLoop: EventLoop) -> EventLoopFuture<T> { self.sync.lock() defer { self.sync.unlock() } if let cached = self.cached, let cacheUntil = self.cacheUntil, Date() < cacheUntil { // If no-cache was set on the header, you *always* have to validate with the server. // must-revalidate does not require checking with the server until after it expires. if self.headers == nil || self.headers?.cacheControl == nil || self.headers?.cacheControl?.noCache == false { return eventLoop.makeSucceededFuture(cached) } } // Don't make a new request if one is already running. if let request = self.request { // The current request may be happening on a different event loop. return request.hop(to: eventLoop) } logger?.debug("Requesting data from \(self.uri)") let request = self.download(on: eventLoop, using: client, logger: logger) self.request = request // Once the request finishes, clear the current request and return the data. return request.map { data in // Synchronize access to shared state self.sync.lock() defer { self.sync.unlock() } self.request = nil return data } } private func download(on eventLoop: EventLoop, using client: Client, logger: Logger?) -> EventLoopFuture<T> { // https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.3.4 var headers: HTTPHeaders = [:] if let eTag = self.headers?.firstValue(name: .eTag) { headers.add(name: .ifNoneMatch, value: eTag) } if let lastModified = self.headers?.lastModified { // TODO: If using HTTP/1.0 then this should be .ifUnmodifiedSince instead. Don't know // how to determine that right now. headers.add(name: .ifModifiedSince, value: lastModified.serialize()) } // Cache-Control max-age is calculated against the request date. let requestSentAt = Date() return client.get( self.uri, headers: headers ).flatMapThrowing { response -> ClientResponse in if !(response.status == .notModified || response.status == .ok) { throw EndpointCacheError.unexpctedResponseStatus(response.status, uri: self.uri) } return response }.flatMap { response -> EventLoopFuture<T> in // Synchronize access to shared state. self.sync.lock() defer { self.sync.unlock() } if let cacheControl = response.headers.cacheControl, cacheControl.noStore == true { // The server *shouldn't* give an expiration with no-store, but... self.clearCache() } else { self.headers = response.headers self.cacheUntil = self.headers?.expirationDate(requestSentAt: requestSentAt) } switch response.status { case .notModified: logger?.debug("Cached data is still valid.") guard let cached = self.cached else { // This shouldn't actually be possible, but just in case. self.clearCache() return self.download(on: eventLoop, using: client, logger: logger) } return eventLoop.makeSucceededFuture(cached) case .ok: logger?.debug("New data received") let data: T do { data = try response.content.decode(T.self) } catch { return eventLoop.makeFailedFuture(EndpointCacheError.contentDecodeFailure(error)) } if self.cacheUntil != nil { self.cached = data } return eventLoop.makeSucceededFuture(data) default: // This shouldn't ever happen due to the previous flatMapThrowing return eventLoop.makeFailedFuture(Abort(.internalServerError)) } }.flatMapError { error -> EventLoopFuture<T> in // Synchronize access to shared state. self.sync.lock() defer { self.sync.unlock() } guard let headers = self.headers, let cached = self.cached else { return eventLoop.makeFailedFuture(error) } if let cacheControl = headers.cacheControl, let cacheUntil = self.cacheUntil { if let staleIfError = cacheControl.staleIfError, cacheUntil.addingTimeInterval(Double(staleIfError)) > Date() { // Can use the data for staleIfError seconds past expiration when the server is non-responsive return eventLoop.makeSucceededFuture(cached) } else if cacheControl.noCache == true && cacheUntil > Date() { // The spec isn't very clear here. If no-cache is present you're supposed to validate with the // server. However, if the server doesn't respond, but I'm still within the expiration time, I'm // opting to say that the cache should be considered usable. return eventLoop.makeSucceededFuture(cached) } } self.clearCache() return eventLoop.makeFailedFuture(error) } } private func clearCache() { self.cached = nil self.headers = nil self.cacheUntil = nil } }
39.611429
121
0.587853
03e1a894d2be2ac834cf42e3d7a3649713d011c8
368
// // StackView.swift // MoviesApplication // // Created by Burak Yılmaz on 30.05.2020. // Copyright © 2020 Burak Yılmaz. All rights reserved. // import Foundation import UIKit //TODO: Removing StackView elements extension UIStackView { func removeAllSubviews() { subviews.forEach { (view) in view.removeFromSuperview() } } }
18.4
55
0.660326
2fe3c19b8355d3b74fa8ddd4dec9fb45b63e9f85
4,890
// // XWStudentRealmTool.swift // XWRealmSwiftDemo // // Created by 邱学伟 on 2018/5/30. // Copyright © 2018年 邱学伟. All rights reserved. // import UIKit import RealmSwift class XWStudentRealmTool: Object { private class func getDB() -> Realm { let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String let dbPath = docPath.appending("/defaultDB.realm") /// 传入路径会自动创建数据库 let defaultRealm = try! Realm(fileURL: URL.init(string: dbPath)!) return defaultRealm } } /// 配置 extension XWStudentRealmTool { /// 配置数据库 public class func configRealm() { /// 如果要存储的数据模型属性发生变化,需要配置当前版本号比之前大 let dbVersion : UInt64 = 3 let docPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as String let dbPath = docPath.appending("/defaultDB.realm") let config = Realm.Configuration(fileURL: URL.init(string: dbPath), inMemoryIdentifier: nil, syncConfiguration: nil, encryptionKey: nil, readOnly: false, schemaVersion: dbVersion, migrationBlock: { (migration, oldSchemaVersion) in migration.enumerateObjects(ofType: Student.className(), { (oldObject, newObject) in let name = oldObject!["name"] as! String newObject!["groupName"] = "兰雄\(name)" }) }, deleteRealmIfMigrationNeeded: false, shouldCompactOnLaunch: nil, objectTypes: nil) Realm.Configuration.defaultConfiguration = config Realm.asyncOpen { (realm, error) in if let _ = realm { print("Realm 服务器配置成功!") }else if let error = error { print("Realm 数据库配置失败:\(error.localizedDescription)") } } } } /// 增 extension XWStudentRealmTool { /// 保存一个Student public class func insertStudent(by student : Student) -> Void { let defaultRealm = self.getDB() try! defaultRealm.write { defaultRealm.add(student) } print(defaultRealm.configuration.fileURL ?? "") } /// 保存一些Student public class func insertStudents(by students : [Student]) -> Void { let defaultRealm = self.getDB() try! defaultRealm.write { defaultRealm.add(students) } print(defaultRealm.configuration.fileURL ?? "") } } /// 查 extension XWStudentRealmTool { /// 获取 所保存的 Student public class func getStudents() -> Results<Student> { let defaultRealm = self.getDB() return defaultRealm.objects(Student.self) } /// 获取 指定id (主键) 的 Student public class func getStudent(from id : Int) -> Student? { let defaultRealm = self.getDB() return defaultRealm.object(ofType: Student.self, forPrimaryKey: id) } /// 获取 指定条件 的 Student public class func getStudentByTerm(_ term: String) -> Results<Student> { let defaultRealm = self.getDB() print(defaultRealm.configuration.fileURL ?? "") let predicate = NSPredicate(format: term) let results = defaultRealm.objects(Student.self) return results.filter(predicate) } /// 获取 学号升降序 的 Student public class func getStudentByIdSorted(_ isAscending: Bool) -> Results<Student> { let defaultRealm = self.getDB() print(defaultRealm.configuration.fileURL ?? "") let results = defaultRealm.objects(Student.self) return results.sorted(byKeyPath: "id", ascending: isAscending) } } /// 改 extension XWStudentRealmTool { /// 更新单个 Student public class func updateStudent(student : Student) { let defaultRealm = self.getDB() try! defaultRealm.write { defaultRealm.add(student, update: true) } } /// 更新多个 Student public class func updateStudent(students : [Student]) { let defaultRealm = self.getDB() try! defaultRealm.write { defaultRealm.add(students, update: true) } } /// 更新多个 Student public class func updateStudentAge(age : Int) { let defaultRealm = self.getDB() try! defaultRealm.write { let students = defaultRealm.objects(Student.self) students.setValue(age, forKey: "age") } } } /// 删 extension XWStudentRealmTool { /// 删除单个 Student public class func deleteStudent(student : Student) { let defaultRealm = self.getDB() try! defaultRealm.write { defaultRealm.delete(student) } } /// 删除多个 Student public class func deleteStudent(students : Results<Student>) { let defaultRealm = self.getDB() try! defaultRealm.write { defaultRealm.delete(students) } } }
33.040541
238
0.634356
76030b5c28f3726bcbd2a76a207c8146b06a3c8d
2,002
/** * Copyright (c) 2019-present, Facebook, 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 WinSDK import SwiftWin32 import CPlaygroundSupport typealias EnumChildProc = @convention(c) (HWND, LPARAM) -> Bool let DestroyChildrenProc: WNDENUMPROC = { (hWnd, lParam) in return WindowsBool(DestroyWindow(hWnd)) } public final class PlaygroundPage { public static let current: PlaygroundPage = PlaygroundPage() public var liveView: View? = nil { didSet { // Don't do anything if we just went from nil to nil. guard !(liveView == nil && oldValue == nil) else { return } if let old = oldValue { EnumChildWindows(old._handle, DestroyChildrenProc, 0) } if let liveView = liveView { let handle = liveView._handle let style = GetWindowLongA(handle, GWL_STYLE) SetWindowLongA(handle, GWL_STYLE, (style | WS_CHILD)) let styleEx = GetWindowLongA(handle, GWL_EXSTYLE) SetWindowLongA(handle, GWL_EXSTYLE, styleEx | WS_EX_MDICHILD) SetParent(handle, g_ui) var rect = RECT() GetClientRect(g_ui, &rect) SetWindowPos(handle, unsafeBitCast(1, to: HWND?.self), rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, UINT(bitPattern: SWP_NOZORDER)); } } } }
37.773585
97
0.628372
f7969f4e1f8ac79a5a6060d92d4ae3e958744889
3,322
// Copyright © 2018 Stormbird PTE. LTD. import Foundation import UIKit protocol DappsHomeViewControllerHeaderViewDelegate: AnyObject { func didExitEditMode(inHeaderView: DappsHomeViewControllerHeaderView) } class DappsHomeViewControllerHeaderView: UICollectionReusableView { private let stackView = [].asStackView(axis: .vertical, contentHuggingPriority: .required, alignment: .center) private let headerView = DappsHomeHeaderView() private let exitEditingModeButton = UIButton(type: .system) weak var delegate: DappsHomeViewControllerHeaderViewDelegate? let myDappsButton = DappButton() let historyButton = DappButton() override init(frame: CGRect) { super.init(frame: frame) let buttonsStackView = [ myDappsButton, .spacerWidth(40), historyButton ].asStackView(distribution: .equalSpacing, contentHuggingPriority: .required) exitEditingModeButton.addTarget(self, action: #selector(exitEditMode), for: .touchUpInside) exitEditingModeButton.translatesAutoresizingMaskIntoConstraints = false addSubview(exitEditingModeButton) stackView.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubviews([ headerView, .spacer(height: 30), buttonsStackView, ]) addSubview(stackView) NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: topAnchor, constant: 50), stackView.leadingAnchor.constraint(equalTo: leadingAnchor), stackView.trailingAnchor.constraint(equalTo: trailingAnchor), stackView.bottomAnchor.constraint(equalTo: exitEditingModeButton.topAnchor, constant: -10), myDappsButton.widthAnchor.constraint(equalTo: historyButton.widthAnchor), exitEditingModeButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20), exitEditingModeButton.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -20), ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure(viewModel: DappsHomeViewControllerHeaderViewViewModel = .init(isEditing: false)) { backgroundColor = viewModel.backgroundColor headerView.configure(viewModel: .init(title: viewModel.title)) myDappsButton.configure(viewModel: .init(image: viewModel.myDappsButtonImage, title: viewModel.myDappsButtonTitle)) historyButton.configure(viewModel: .init(image: viewModel.historyButtonImage, title: viewModel.historyButtonTitle)) if viewModel.isEditing { exitEditingModeButton.isHidden = false exitEditingModeButton.setTitle(R.string.localizable.done().localizedUppercase, for: .normal) exitEditingModeButton.titleLabel?.font = Fonts.bold(size: 12) myDappsButton.isEnabled = false historyButton.isEnabled = false } else { exitEditingModeButton.isHidden = true myDappsButton.isEnabled = true historyButton.isEnabled = true } } @objc private func exitEditMode() { configure(viewModel: .init(isEditing: false)) delegate?.didExitEditMode(inHeaderView: self) } }
38.627907
123
0.706502
eb4ec1cbb1a97b4325de5ef859e93709366cbe64
1,410
// // AppDelegate.swift // JerryKit // // Created by Jayyi on 2020/10/3. // Copyright © 2020 Jerry987123. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.105263
179
0.747518
64fa750e05871c2fac53a46f5fba8838a5d83e9b
1,234
// // StudentAppTests.swift // StudentAppTests // // Created by Naguru Abdur,Rehaman on 3/24/22. // import XCTest @testable import StudentApp class StudentAppTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testExample() throws { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. // Any test you write for XCTest can be annotated as throws and async. // Mark your test throws to produce an unexpected failure when your test encounters an uncaught error. // Mark your test async to allow awaiting for asynchronous code to complete. Check the results with assertions afterwards. } func testPerformanceExample() throws { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
33.351351
130
0.686386
5d037d6962021970834fe79909e4f3c48961b427
764
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck protocol A { extension String { } typealias e: e() } func a: S) { return S.C() -> : C { typealias g<T, V, Any, x in a { typealias e = A) { } class A? = e: A? { } return { c() { } } } case .Iterator.substringWithRange(b(x) { b() -> == b(T) { } class a { } } func c, a<A> () { d: T? { func b> { } typealias b : Sequence, AnyObject> { } } class A { } let g = .E == c }
18.190476
79
0.641361
1cfea3fad5367234ed919b4f222d27b13f1b465f
1,567
// // CSVImporter.swift // Dining Hall // // Created by Femi Lamptey on 10/08/2018. // Copyright © 2018 Femi Lamptey. All rights reserved. // import Foundation class CSVImporter { private init() { /* Static class, no need for initializer */ } private static func process(contents: String) throws -> [ImportedStudent] { var importedStudents: [ImportedStudent] = [] let rows = contents.components(separatedBy: "\n") var tables: [String] = [] for row in rows { let data = row.components(separatedBy: ",") let table = data[0] if let column = table.first { DatabaseManager.addTable(tableName: table, column: "\(column)") } tables.append(table) if data.count != 1 { for i in 1...data.count - 1 { if data[i] != " " { let trimmedName = data[i].components(separatedBy: NSCharacterSet.whitespacesAndNewlines).joined(separator: " ") let student = ImportedStudent(fullName: trimmedName, seatingArrangement: table) importedStudents.append(student) } } } } return importedStudents } public static func processFile(path: URL) throws -> [ImportedStudent] { let contents = try String.init(contentsOf: path); do {} return try process(contents: contents) } }
29.566038
135
0.530313
edc84b2e96334c42be7c74a1637cf8d9f4a1bed8
1,333
// // BookCell.swift // Books // // Created by Katherine Li on 9/15/20. // Copyright © 2020 Katherine Li. All rights reserved. // import SwiftUI struct BookCell: View { enum Constants { static let bookMark = "Book Mark" } let book: Book @State var chapter: String = "" var body: some View { return VStack(alignment: .leading) { HStack { Text(book.name).fontWeight(.bold) Text(book.author).foregroundColor(.gray).font(.system(size: 15)) Text(book.version).foregroundColor(.pink).font(.system(size: 14)) } Button(action: { self.openBookLink(link: self.book.link) }) { Text(book.link).foregroundColor(.blue).underline() } HStack { Text(Constants.bookMark + ":").foregroundColor(.orange).font(.system(size: 15)) TextField("Enter Chapter Number", text: $chapter).foregroundColor(.orange).font(.system(size: 15)) } } } func openBookLink(link: String) { if let url = URL(string: link) { if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } } }
28.361702
114
0.538635
2272fb1dd2d6a18008b9d84321f811d4e541c26d
268
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class A<T where T : A { var f : a { } } protocol a { enum A { var b { { { } { } } { } { } func b {
11.652174
87
0.645522
1e3a0d150468348746ac9a9a820f3414cf854b70
1,628
import Foundation import ErgonomicCodable public struct LiveGameInfo: Codable, BasicMatchInfo { public var id: Match.ID public var players: [PlayerInfo] public var state: State public var mapID: MapID public var modeID: GameMode.ID public var provisioningFlowID: ProvisioningFlow.ID public var matchmakingData: MatchmakingData? public var isReconnectable: Bool public var queueID: QueueID? { matchmakingData?.queueID } public var isRanked: Bool { matchmakingData?.isRanked ?? false } private enum CodingKeys: String, CodingKey { case id = "MatchID" case players = "Players" case state = "State" case mapID = "MapID" case modeID = "ModeID" case provisioningFlowID = "ProvisioningFlow" case matchmakingData = "MatchmakingData" case isReconnectable = "IsReconnectable" } public struct State: SimpleRawWrapper { static let inProgress = Self("IN_PROGRESS") public var rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } } public struct MatchmakingData: Codable { @SpecialOptional(.emptyString) public var queueID: QueueID? public var isRanked: Bool private enum CodingKeys: String, CodingKey { case queueID = "QueueID" case isRanked = "IsRanked" } } public struct PlayerInfo: Codable, Identifiable { public var id: Player.ID public var teamID: Team.ID public var agentID: Agent.ID public var identity: Player.Identity private enum CodingKeys: String, CodingKey { case id = "Subject" case teamID = "TeamID" case agentID = "CharacterID" case identity = "PlayerIdentity" } } }
22
53
0.72113
ac224a73e0afb5afb83f04bc59c80c66971936e1
2,140
// // AppDelegate.swift // LoadingView // // Created by LiChendi on 16/2/17. // Copyright © 2016年 LiChendi. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. 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:. } }
45.531915
285
0.754206
d65110cfdf3d388c166891fea0248013ac58c868
4,395
// swift-tools-version:5.0 import PackageDescription import Foundation var unsupportedTests: Set<String> = ["ObjectiveCNoBridgingStubs"] #if !os(macOS) && !os(iOS) && !os(watchOS) && !os(tvOS) unsupportedTests.insert("ObjectiveCBridging") unsupportedTests.insert("ObjectiveCBridgingStubs") #endif //===--- // Single Source Libraries // /// Return the source files in subDirectory that we will translate into /// libraries. Each source library will be compiled as its own module. func getSingleSourceLibraries(subDirectory: String) -> [String] { let f = FileManager.`default` let dirURL = URL(fileURLWithPath: subDirectory) let fileURLs = try! f.contentsOfDirectory(at: dirURL, includingPropertiesForKeys: nil) return fileURLs.compactMap { (path: URL) -> String? in let c = path.lastPathComponent.split(separator: ".") // Too many components. Must be a gyb file. if c.count > 2 { return nil } if c[1] != "swift" { return nil } let name = String(c[0]) // We do not support this test. if unsupportedTests.contains(name) { return nil } return name } } var singleSourceLibraryDirs: [String] = [] singleSourceLibraryDirs.append("single-source") var singleSourceLibraries: [String] = singleSourceLibraryDirs.flatMap { getSingleSourceLibraries(subDirectory: $0) } //===--- // Multi Source Libraries // func getMultiSourceLibraries(subDirectory: String) -> [(String, String)] { let f = FileManager.`default` let dirURL = URL(string: subDirectory)! let subDirs = try! f.contentsOfDirectory(at: dirURL, includingPropertiesForKeys: nil) return subDirs.map { (subDirectory, $0.lastPathComponent) } } var multiSourceLibraryDirs: [String] = [] multiSourceLibraryDirs.append("multi-source") var multiSourceLibraries: [(parentSubDir: String, name: String)] = multiSourceLibraryDirs.flatMap { getMultiSourceLibraries(subDirectory: $0) } //===--- // Products // var products: [Product] = [] products.append(.library(name: "TestsUtils", type: .static, targets: ["TestsUtils"])) products.append(.library(name: "DriverUtils", type: .static, targets: ["DriverUtils"])) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) products.append(.library(name: "ObjectiveCTests", type: .static, targets: ["ObjectiveCTests"])) #endif products.append(.executable(name: "SwiftBench", targets: ["SwiftBench"])) products += singleSourceLibraries.map { .library(name: $0, type: .static, targets: [$0]) } products += multiSourceLibraries.map { return .library(name: $0.name, type: .static, targets: [$0.name]) } //===--- // Targets // var targets: [Target] = [] targets.append(.target(name: "TestsUtils", path: "utils", sources: ["TestsUtils.swift"])) targets.append(.systemLibrary(name: "LibProc", path: "utils/LibProc")) targets.append( .target(name: "DriverUtils", dependencies: [.target(name: "TestsUtils"), "LibProc"], path: "utils", sources: ["DriverUtils.swift", "ArgParse.swift"])) var swiftBenchDeps: [Target.Dependency] = [.target(name: "TestsUtils")] #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) swiftBenchDeps.append(.target(name: "ObjectiveCTests")) #endif swiftBenchDeps.append(.target(name: "DriverUtils")) swiftBenchDeps += singleSourceLibraries.map { .target(name: $0) } swiftBenchDeps += multiSourceLibraries.map { .target(name: $0.name) } targets.append( .target(name: "SwiftBench", dependencies: swiftBenchDeps, path: "utils", sources: ["main.swift"])) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) targets.append( .target(name: "ObjectiveCTests", path: "utils/ObjectiveCTests", publicHeadersPath: ".")) #endif var singleSourceDeps: [Target.Dependency] = [.target(name: "TestsUtils")] #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) singleSourceDeps.append(.target(name: "ObjectiveCTests")) #endif targets += singleSourceLibraries.map { name in return .target(name: name, dependencies: singleSourceDeps, path: "single-source", sources: ["\(name).swift"]) } targets += multiSourceLibraries.map { lib in return .target( name: lib.name, dependencies: [ .target(name: "TestsUtils") ], path: lib.parentSubDir) } //===--- // Top Level Definition // let p = Package( name: "swiftbench", products: products, targets: targets, swiftLanguageVersions: [.v4] )
29.10596
99
0.686234
3ac683a51d305a7549e8d1a95405f125316b1efd
3,541
// // SimpleAudioQueueVC.swift // ModernAVPlayer_Example // // Created by ankierman on 22/05/2020. // Copyright © 2020 CocoaPods. All rights reserved. // import ModernAVPlayer import RxSwift import RxCocoa import UIKit final class SimpleAudioQueueVC: UIViewController { // MARK: - Inputs private let player: ModernAVPlayer = { let conf = PlayerConfigurationExample() return ModernAVPlayer(config: conf, loggerDomains: [.error, .unavailableCommand]) }() private let library = ModernAudioQueueLibrary() private lazy var remote: AudioQueueRemoteExample = { return AudioQueueRemoteExample(player: self.player, library: self.library) }() private var playNext: Disposable? private let disposeBag = DisposeBag() // MARK: - Interface Buidler @IBOutlet weak private var mediaLabel: UILabel! @IBOutlet weak private var stateLabel: UILabel! @IBOutlet weak private var timingLabel: UILabel! @IBOutlet weak private var itemDuration: UILabel! // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() title = "Simple Audio Queue" setupRxLabels() player.remoteCommands = remote.defaultCommands setupRemoteCallback() loadMedia() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) playNext?.dispose() } private func setupRxLabels() { player.rx.state .map({ "State: " + $0.description }) .bind(to: stateLabel.rx.text) .disposed(by: disposeBag) player.rx.currentTime .map({ "Current time: " + $0.description }) .bind(to: timingLabel.rx.text) .disposed(by: disposeBag) player.rx.itemDuration .map({ if let txt = $0?.description { return "Duration: " + txt } else { return "Duration is nil" } }) .bind(to: itemDuration.rx.text) .disposed(by: disposeBag) } @IBAction func setupPlayNext(_ sender: UISwitch) { guard sender.isOn else { playNext?.dispose() playNext = nil return } playNext = player.rx.itemPlayToEndTime .subscribe(onNext: { [weak self] _ in DispatchQueue.main.async { self?.loadMedia(userAction: .nextTrack) } }) } private func setupMediaIndexLabel(index: String) { mediaLabel.text = "Media index: " + index } private func setupRemoteCallback() { remote.selectedMediaIndexChanged = { [weak self] index in self?.setupMediaIndexLabel(index: index) } } // MARK: - Commands @IBAction func play(_ sender: UIButton) { player.play() } @IBAction func pause(_ sender: UIButton) { player.pause() } @IBAction func stop(_ sender: Any) { player.stop() } @IBAction func prevSeek(_ sender: UIButton) { loadMedia(userAction: .prevTrack) } @IBAction func nextSeek(_ sender: UIButton) { loadMedia(userAction: .nextTrack) } private func loadMedia(userAction: ModernAudioQueueLibrary.UserAction? = nil) { if let action = userAction { library.changeMedia(userAction: action) } setupMediaIndexLabel(index: library.index.description) let media = library.selectedMedia player.load(media: media, autostart: true) } }
26.62406
89
0.608868