| repo_name
				 stringlengths 6 91 | path
				 stringlengths 6 999 | copies
				 stringclasses 283
				values | size
				 stringlengths 1 7 | content
				 stringlengths 3 1.05M | license
				 stringclasses 15
				values | 
|---|---|---|---|---|---|
| 
	hooman/swift | 
	test/decl/protocol/special/coding/enum_codable_invalid_codingkeys.swift | 
	3 | 
	2032 | 
	// RUN: %target-typecheck-verify-swift -verify-ignore-unknown
// Enums with a CodingKeys entity which is not a type should not derive
// conformance.
enum InvalidCodingKeys1 : Codable { // expected-error {{type 'InvalidCodingKeys1' does not conform to protocol 'Decodable'}}
// expected-error@-1 {{type 'InvalidCodingKeys1' does not conform to protocol 'Encodable'}}
  static let CodingKeys = 5 // expected-note {{cannot automatically synthesize 'Decodable' because 'CodingKeys' is not an enum}}
  // expected-note@-1 {{cannot automatically synthesize 'Encodable' because 'CodingKeys' is not an enum}}
}
// Enums with a CodingKeys entity which does not conform to CodingKey should
// not derive conformance.
enum InvalidCodingKeys2 : Codable { // expected-error {{type 'InvalidCodingKeys2' does not conform to protocol 'Decodable'}}
  // expected-error@-1 {{type 'InvalidCodingKeys2' does not conform to protocol 'Encodable'}}
  enum CodingKeys {} // expected-note {{cannot automatically synthesize 'Decodable' because 'CodingKeys' does not conform to CodingKey}}
  // expected-note@-1 {{cannot automatically synthesize 'Encodable' because 'CodingKeys' does not conform to CodingKey}}
}
// Enums with a CodingKeys entity which is not an enum should not derive
// conformance.
enum InvalidCodingKeys3 : Codable { // expected-error {{type 'InvalidCodingKeys3' does not conform to protocol 'Decodable'}}
  // expected-error@-1 {{type 'InvalidCodingKeys3' does not conform to protocol 'Encodable'}}
  struct CodingKeys : CodingKey { // expected-note {{cannot automatically synthesize 'Decodable' because 'CodingKeys' is not an enum}}
    // expected-note@-1 {{cannot automatically synthesize 'Encodable' because 'CodingKeys' is not an enum}}
      var stringValue: String
      init?(stringValue: String) {
          self.stringValue = stringValue
          self.intValue = nil
      }
      var intValue: Int?
      init?(intValue: Int) {
          self.stringValue = "\(intValue)"
          self.intValue = intValue
      }
  }
}
 | 
	apache-2.0 | 
| 
	lorentey/swift | 
	test/SILGen/vtables_multifile.swift | 
	4 | 
	22343 | 
	// RUN: %target-swift-emit-silgen %s | %FileCheck %s
// RUN: %target-swift-emit-silgen %s -primary-file %S/Inputs/vtables_multifile_2.swift | %FileCheck %S/Inputs/vtables_multifile_2.swift
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module %s -enable-library-evolution -emit-module-path %t/vtables_multifile.swiftmodule
// RUN: %target-swift-emit-silgen %S/Inputs/vtables_multifile_3.swift -I %t | %FileCheck %S/Inputs/vtables_multifile_3.swift
open class Base<T> {
  fileprivate func privateMethod1() {}
  fileprivate func privateMethod2(_: AnyObject) {}
  fileprivate func privateMethod3(_: Int) {}
  fileprivate func privateMethod4(_: T) {}
}
open class Derived : Base<Int> {
  internal override func privateMethod1() {} // ABI compatible override with same type
  internal override func privateMethod2(_: AnyObject?) {} // ABI compatible override with different type
  internal override func privateMethod3(_: Int?) {} // Requires thunking, different type
  internal override func privateMethod4(_: Int) {} // Requires thunking, same type
}
open class MoreDerived : Derived {
  public override func privateMethod1() {}
  public override func privateMethod2(_: AnyObject?) {}
  public override func privateMethod3(_: Int?) {}
  public override func privateMethod4(_: Int) {}
}
open class MostDerived : MoreDerived {
  open override func privateMethod1() {}
  open override func privateMethod2(_: AnyObject?) {}
  open override func privateMethod3(_: Int?) {}
  open override func privateMethod4(_: Int) {}
}
public final class FinalDerived : Base<Int> {
  internal override func privateMethod1() {}
  internal override func privateMethod2(_: AnyObject?) {}
  internal override func privateMethod3(_: Int?) {}
  internal override func privateMethod4(_: Int) {}
}
// See Inputs/vtables_multifile_2.swift for overrides in a different file.
// See Inputs/vtables_multifile_3.swift for overrides in a different module.
// --
// VTable thunks for the more visible overrides of less visible methods dispatch to the
// vtable slot for the more visible method.
// --
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV : $@convention(method) (@guaranteed Derived) -> () {
// CHECK: bb0(%0 : @guaranteed $Derived):
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %0 : $Derived, #Derived.privateMethod1!1 : (Derived) -> () -> (), $@convention(method) (@guaranteed Derived) -> ()
// CHECK-NEXT:  apply [[METHOD]](%0) : $@convention(method) (@guaranteed Derived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> () {
// CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>, %1 : @guaranteed $Derived):
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod2!1 : (Derived) -> (AnyObject?) -> (), $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> ()
// CHECK-NEXT:  apply [[METHOD]](%0, %1) : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV : $@convention(method) (Int, @guaranteed Derived) -> () {
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $Derived):
// CHECK-NEXT:  [[ARG:%.*]] = enum $Optional<Int>, #Optional.some!enumelt.1, %0 : $Int
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod3!1 : (Derived) -> (Int?) -> (), $@convention(method) (Optional<Int>, @guaranteed Derived) -> ()
// CHECK-NEXT:  apply %3(%2, %1) : $@convention(method) (Optional<Int>, @guaranteed Derived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed Derived) -> () {
// CHECK: bb0(%0 : $*Int, %1 : @guaranteed $Derived):
// CHECK-NEXT:  [[ARG:%.*]] = load [trivial] %0 : $*Int
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod4!1 : (Derived) -> (Int) -> (), $@convention(method) (Int, @guaranteed Derived) -> ()
// CHECK-NEXT:  apply %3(%2, %1) : $@convention(method) (Int, @guaranteed Derived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// --
// The subclass can see both the methods of Base and the methods of Derived,
// so it overrides both with thunks that dispatch to methods of MoreDerived.
// --
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV : $@convention(method) (@guaranteed MoreDerived) -> ()
// CHECK: bb0(%0 : @guaranteed $MoreDerived):
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %0 : $MoreDerived, #MoreDerived.privateMethod1!1 : (MoreDerived) -> () -> (), $@convention(method) (@guaranteed MoreDerived) -> ()
// CHECK-NEXT:  apply [[METHOD]](%0) : $@convention(method) (@guaranteed MoreDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> () {
// CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>, %1 : @guaranteed $MoreDerived):
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod2!1 : (MoreDerived) -> (AnyObject?) -> (), $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  apply [[METHOD]](%0, %1) : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV : $@convention(method) (Int, @guaranteed MoreDerived) -> () {
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $MoreDerived):
// CHECK-NEXT:  [[ARG:%.*]] = enum $Optional<Int>, #Optional.some!enumelt.1, %0 : $Int
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod3!1 : (MoreDerived) -> (Int?) -> (), $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  apply %3(%2, %1) : $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed MoreDerived) -> () {
// CHECK: bb0(%0 : $*Int, %1 : @guaranteed $MoreDerived):
// CHECK-NEXT:  [[ARG:%.*]] = load [trivial] %0 : $*Int
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod4!1 : (MoreDerived) -> (Int) -> (), $@convention(method) (Int, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  apply %3(%2, %1) : $@convention(method) (Int, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// --
// Thunks override methods of Derived as well.
// --
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod1yyFAA0D0CADyyFTV : $@convention(method) (@guaranteed MoreDerived) -> () {
// CHECK: bb0(%0 : @guaranteed $MoreDerived):
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %0 : $MoreDerived, #MoreDerived.privateMethod1!1 : (MoreDerived) -> () -> (), $@convention(method) (@guaranteed MoreDerived) -> ()
// CHECK-NEXT:  apply [[METHOD]](%0) : $@convention(method) (@guaranteed MoreDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgFAA0D0CADyyAEFTV : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> () {
// CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>, %1 : @guaranteed $MoreDerived):
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod2!1 : (MoreDerived) -> (AnyObject?) -> (), $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  apply [[METHOD]](%0, %1) : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgFAA0D0CADyyAEFTV : $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> () {
// CHECK: bb0(%0 : $Optional<Int>, %1 : @guaranteed $MoreDerived):
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod3!1 : (MoreDerived) -> (Int?) -> (), $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  apply [[METHOD]](%0, %1) : $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiFAA0D0CADyySiFTV : $@convention(method) (Int, @guaranteed MoreDerived) -> () {
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $MoreDerived):
// CHECK-NEXT:  [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod4!1 : (MoreDerived) -> (Int) -> (), $@convention(method) (Int, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  apply [[METHOD]](%0, %1) : $@convention(method) (Int, @guaranteed MoreDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// --
// Thunks for final overrides do not re-dispatch, even if the override is more
// visible.
// --
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile12FinalDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV : $@convention(method) (Int, @guaranteed FinalDerived) -> () {
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $FinalDerived):
// CHECK-NEXT:  [[ARG:%.*]] = enum $Optional<Int>, #Optional.some!enumelt.1, %0 : $Int // user: %4
// CHECK:       [[METHOD:%.*]] = function_ref @$s17vtables_multifile12FinalDerivedC14privateMethod3yySiSgF : $@convention(method) (Optional<Int>, @guaranteed FinalDerived) -> ()
// CHECK-NEXT:  apply [[METHOD]]([[ARG]], %1) : $@convention(method) (Optional<Int>, @guaranteed FinalDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile12FinalDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed FinalDerived) -> () {
// CHECK: bb0(%0 : $*Int, %1 : @guaranteed $FinalDerived):
// CHECK-NEXT:  [[ARG:%.*]] = load [trivial] %0 : $*Int
// CHECK:       [[METHOD:%.*]] = function_ref @$s17vtables_multifile12FinalDerivedC14privateMethod4yySiF : $@convention(method) (Int, @guaranteed FinalDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = apply [[METHOD]]([[ARG]], %1) : $@convention(method) (Int, @guaranteed FinalDerived) -> ()
// CHECK-NEXT:  [[RESULT:%.*]] = tuple ()
// CHECK-NEXT:  return [[RESULT]] : $()
// CHECK-NEXT: }
// --
// VTable for Derived.
// --
// CHECK-LABEL: sil_vtable [serialized] Derived {
// CHECK-NEXT:   #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile7DerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV [override]  // vtable thunk for Base.privateMethod1() dispatching to Derived.privateMethod1()
// CHECK-NEXT:   #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV [override] // vtable thunk for Base.privateMethod2(_:) dispatching to Derived.privateMethod2(_:)
// CHECK-NEXT:   #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile7DerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [override] // vtable thunk for Base.privateMethod3(_:) dispatching to Derived.privateMethod3(_:)
// CHECK-NEXT:   #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile7DerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [override]      // vtable thunk for Base.privateMethod4(_:) dispatching to Derived.privateMethod4(_:)
// CHECK-NEXT:   #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile7DerivedCACycfC [override]        // Derived.__allocating_init()
// CHECK-NEXT:   #Derived.privateMethod1!1: (Derived) -> () -> () : @$s17vtables_multifile7DerivedC14privateMethod1yyF // Derived.privateMethod1()
// CHECK-NEXT:   #Derived.privateMethod2!1: (Derived) -> (AnyObject?) -> () : @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgF  // Derived.privateMethod2(_:)
// CHECK-NEXT:   #Derived.privateMethod3!1: (Derived) -> (Int?) -> () : @$s17vtables_multifile7DerivedC14privateMethod3yySiSgF // Derived.privateMethod3(_:)
// CHECK-NEXT:   #Derived.privateMethod4!1: (Derived) -> (Int) -> () : @$s17vtables_multifile7DerivedC14privateMethod4yySiF    // Derived.privateMethod4(_:)
// CHECK-NEXT:   #Derived.deinit!deallocator.1: @$s17vtables_multifile7DerivedCfD      // Derived.__deallocating_deinit
// CHECK-NEXT: }
// --
// VTable for MoreDerived.
// --
// CHECK-LABEL: sil_vtable [serialized] MoreDerived {
// CHECK-NEXT:   #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV [override]     // vtable thunk for Base.privateMethod1() dispatching to MoreDerived.privateMethod1()
// CHECK-NEXT:   #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV [override]    // vtable thunk for Base.privateMethod2(_:) dispatching to MoreDerived.privateMethod2(_:)
// CHECK-NEXT:   #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [override]    // vtable thunk for Base.privateMethod3(_:) dispatching to MoreDerived.privateMethod3(_:)
// CHECK-NEXT:   #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [override] // vtable thunk for Base.privateMethod4(_:) dispatching to MoreDerived.privateMethod4(_:)
// CHECK-NEXT:   #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile11MoreDerivedCACycfC [override]   // MoreDerived.__allocating_init()
// CHECK-NEXT:   #Derived.privateMethod1!1: (Derived) -> () -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod1yyFAA0D0CADyyFTV [override]     // vtable thunk for Derived.privateMethod1() dispatching to MoreDerived.privateMethod1()
// CHECK-NEXT:   #Derived.privateMethod2!1: (Derived) -> (AnyObject?) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgFAA0D0CADyyAEFTV [override]    // vtable thunk for Derived.privateMethod2(_:) dispatching to MoreDerived.privateMethod2(_:)
// CHECK-NEXT:   #Derived.privateMethod3!1: (Derived) -> (Int?) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgFAA0D0CADyyAEFTV [override]   // vtable thunk for Derived.privateMethod3(_:) dispatching to MoreDerived.privateMethod3(_:)
// CHECK-NEXT:   #Derived.privateMethod4!1: (Derived) -> (Int) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiFAA0D0CADyySiFTV [override]      // vtable thunk for Derived.privateMethod4(_:) dispatching to MoreDerived.privateMethod4(_:)
// CHECK-NEXT:   #MoreDerived.privateMethod1!1: (MoreDerived) -> () -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod1yyF    // MoreDerived.privateMethod1()
// CHECK-NEXT:   #MoreDerived.privateMethod2!1: (MoreDerived) -> (AnyObject?) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgF     // MoreDerived.privateMethod2(_:)
// CHECK-NEXT:   #MoreDerived.privateMethod3!1: (MoreDerived) -> (Int?) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgF    // MoreDerived.privateMethod3(_:)
// CHECK-NEXT:   #MoreDerived.privateMethod4!1: (MoreDerived) -> (Int) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiF       // MoreDerived.privateMethod4(_:)
// CHECK-NEXT:   #MoreDerived.deinit!deallocator.1: @$s17vtables_multifile11MoreDerivedCfD     // MoreDerived.__deallocating_deinit
// CHECK-NEXT: }
// --
// MostDerived just makes public methods open, which does not require thunking.
// --
// CHECK-LABEL: sil_vtable [serialized] MostDerived {
// CHECK-NEXT:   #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile11MostDerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV [override]     // vtable thunk for Base.privateMethod1() dispatching to MostDerived.privateMethod1()
// CHECK-NEXT:   #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV [override]    // vtable thunk for Base.privateMethod2(_:) dispatching to MostDerived.privateMethod2(_:)
// CHECK-NEXT:   #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [override]    // vtable thunk for Base.privateMethod3(_:) dispatching to MostDerived.privateMethod3(_:)
// CHECK-NEXT:   #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [override] // vtable thunk for Base.privateMethod4(_:) dispatching to MostDerived.privateMethod4(_:)
// CHECK-NEXT:   #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile11MostDerivedCACycfC [override]   // MostDerived.__allocating_init()
// CHECK-NEXT:   #Derived.privateMethod1!1: (Derived) -> () -> () : @$s17vtables_multifile11MostDerivedC14privateMethod1yyFAA0D0CADyyFTV [override]     // vtable thunk for Derived.privateMethod1() dispatching to MostDerived.privateMethod1()
// CHECK-NEXT:   #Derived.privateMethod2!1: (Derived) -> (AnyObject?) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod2yyyXlSgFAA0D0CADyyAEFTV [override]    // vtable thunk for Derived.privateMethod2(_:) dispatching to MostDerived.privateMethod2(_:)
// CHECK-NEXT:   #Derived.privateMethod3!1: (Derived) -> (Int?) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod3yySiSgFAA0D0CADyyAEFTV [override]   // vtable thunk for Derived.privateMethod3(_:) dispatching to MostDerived.privateMethod3(_:)
// CHECK-NEXT:   #Derived.privateMethod4!1: (Derived) -> (Int) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod4yySiFAA0D0CADyySiFTV [override]      // vtable thunk for Derived.privateMethod4(_:) dispatching to MostDerived.privateMethod4(_:)
// CHECK-NEXT:   #MoreDerived.privateMethod1!1: (MoreDerived) -> () -> () : @$s17vtables_multifile11MostDerivedC14privateMethod1yyF [override] // MostDerived.privateMethod1()
// CHECK-NEXT:   #MoreDerived.privateMethod2!1: (MoreDerived) -> (AnyObject?) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod2yyyXlSgF [override] // MostDerived.privateMethod2(_:)
// CHECK-NEXT:   #MoreDerived.privateMethod3!1: (MoreDerived) -> (Int?) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod3yySiSgF [override] // MostDerived.privateMethod3(_:)
// CHECK-NEXT:   #MoreDerived.privateMethod4!1: (MoreDerived) -> (Int) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod4yySiF [override] // MostDerived.privateMethod4(_:)
// CHECK-NEXT:   #MostDerived.deinit!deallocator.1: @$s17vtables_multifile11MostDerivedCfD     // MostDerived.__deallocating_deinit
// CHECK-NEXT: }
// --
// FinalDerived adds a final override; make sure we handle this correctly.
// --
// CHECK-LABEL: sil_vtable [serialized] FinalDerived {
// CHECK-NEXT:   #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile12FinalDerivedC14privateMethod1yyF [override]	// FinalDerived.privateMethod1()
// CHECK-NEXT:   #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile12FinalDerivedC14privateMethod2yyyXlSgF [override]	// FinalDerived.privateMethod2(_:)
// CHECK-NEXT:   #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile12FinalDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [override]	// vtable thunk for Base.privateMethod3(_:) dispatching to FinalDerived.privateMethod3(_:)
// CHECK-NEXT:   #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile12FinalDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [override]	// vtable thunk for Base.privateMethod4(_:) dispatching to FinalDerived.privateMethod4(_:)
// CHECK-NEXT:   #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile12FinalDerivedCACycfC [override]	// FinalDerived.__allocating_init()
// CHECK-NEXT:   #FinalDerived.deinit!deallocator.1: @$s17vtables_multifile12FinalDerivedCfD	// FinalDerived.__deallocating_deinit
// CHECK-NEXT: }
 | 
	apache-2.0 | 
| 
	vector-im/vector-ios | 
	Riot/Modules/Application/ScreenNavigation/ScreenPresentationParameters.swift | 
	1 | 
	2457 | 
	// 
// Copyright 2021 New Vector 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
/// Screen presentation parameters used when a universal link is triggered
@objcMembers
class ScreenPresentationParameters: NSObject {
    
    // MARK: - Properties
    
    /// Indicate to pop to home and restore initial view hierarchy
    let restoreInitialDisplay: Bool
    
    /// Indicate to stack above visible views
    /// If this variable is set to true `restoreInitialDisplay` should be set to false to have effect
    let stackAboveVisibleViews: Bool
    
    /// The object that triggers the universal link action.
    let sender: AnyObject?
    
    /// The view containing the anchor rectangle for the popover. Useful for iPad if a universlink trigger a pop over.
    let sourceView: UIView?
        
    /// The view controller from which the universal link is triggered. `nil` if triggered from some other kind of object.
    var presentingViewController: UIViewController? {
        return self.sender as? UIViewController
    }
    
    // MARK: - Properties
    
    init(restoreInitialDisplay: Bool,
         stackAboveVisibleViews: Bool,
         sender: AnyObject?,
         sourceView: UIView?) {
        self.restoreInitialDisplay = restoreInitialDisplay
        self.stackAboveVisibleViews = stackAboveVisibleViews
        self.sender = sender
        self.sourceView = sourceView
        
        super.init()
    }    
    
    convenience init(restoreInitialDisplay: Bool, stackAboveVisibleViews: Bool) {
        self.init(restoreInitialDisplay: restoreInitialDisplay, stackAboveVisibleViews: stackAboveVisibleViews, sender: nil, sourceView: nil)
    }
    
    /// In this initializer `stackAboveVisibleViews` is set to false`
    convenience init(restoreInitialDisplay: Bool) {
        self.init(restoreInitialDisplay: restoreInitialDisplay, stackAboveVisibleViews: false, sender: nil, sourceView: nil)
    }
}
 | 
	apache-2.0 | 
| 
	hanjoes/BitSet | 
	Tests/LinuxMain.swift | 
	1 | 
	93 | 
	import XCTest
@testable import BitSetTests
XCTMain([
    testCase(BitSetTests.allTests),
])
 | 
	mit | 
| 
	BlakeBarrett/wndw | 
	wtrmrkr/VideoPreviewPlayerViewController.swift | 
	1 | 
	804 | 
	//
//  VideoPreviewPlayerViewController.swift
//  wndw
//
//  Created by Blake Barrett on 6/9/16.
//  Copyright © 2016 Blake Barrett. All rights reserved.
//
import Foundation
import AVFoundation
import AVKit
class VideoPreviewPlayerViewController: UIViewController {
    
    var url :NSURL?
    var player :AVPlayer?
    
    override func viewDidLoad() {
        guard let url = url else { return }
        self.player = AVPlayer(URL: url)
        let playerController = AVPlayerViewController()
        playerController.player = player
        
        self.addChildViewController(playerController)
        self.view.addSubview(playerController.view)
        playerController.view.frame = self.view.frame
    }
    
    override func viewDidAppear(animated: Bool) {
        player?.play()
    }
}
 | 
	mit | 
| 
	aquarchitect/MyKit | 
	Sources/iOS/Frameworks/CollectionLayout/Parapoloid/ParaboloidFlowLayout.swift | 
	1 | 
	1424 | 
	// 
// ParaboloidFlowLayout.swift
// MyKit
// 
// Created by Hai Nguyen.
// Copyright (c) 2015 Hai Nguyen.
// 
import UIKit
open class ParaboloidFlowLayout: SnappingFlowLayout {
    // MARK: Property
    open var paraboloidControler: ParaboloidLayoutController?
    open override class var layoutAttributesClass: AnyClass {
        return ParaboloidLayoutAttributes.self
    }
    // MARK: System Methods
    open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return super.layoutAttributesForElements(in: rect)?.map {
            if $0.representedElementCategory == .cell {
                return self.layoutAttributesForItem(at: $0.indexPath) ?? $0
            } else {
                return $0
            }
        }
    }
    open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return (super.layoutAttributesForItem(at: indexPath)?.copy() as? ParaboloidLayoutAttributes).flatMap {
            guard let contentOffset = self.collectionView?.contentOffset else { return nil }
            let center = $0.center.convertToCoordinate(of: contentOffset)
            $0.paraboloidValue = paraboloidControler?.zValue(atPoint: center)
            return $0
        }
    }
}
 | 
	mit | 
| 
	the-blue-alliance/the-blue-alliance-ios | 
	Frameworks/MyTBAKit/Sources/Models/MyTBASubscription.swift | 
	1 | 
	2912 | 
	import Foundation
// https://github.com/the-blue-alliance/the-blue-alliance/blob/364d6da2f3fc464deef5ba580ea37b6cd2816c4a/consts/notification_type.py
public enum NotificationType: String, Codable {
    case upcomingMatch = "upcoming_match"
    case matchScore = "match_score"
    case levelStarting = "starting_comp_level"
    case allianceSelection = "alliance_selection"
    case awards = "awards_posted"
    case mediaPosted = "media_posted"
    case districtPointsUpdated = "district_points_updated"
    case scheduleUpdated = "schedule_updated"
    case finalResults = "final_results"
    case ping = "ping"
    case broadcast = "broadcast"
    case matchVideo = "match_video"
    case eventMatchVideo = "event_match_video"
    case updateFavorites = "update_favorites"
    case updateSubscription = "update_subscriptions"
    case verification = "verification"
    public func displayString() -> String {
        switch self {
        case .upcomingMatch:
            return "Upcoming Match"
        case .matchScore:
            return "Match Score"
        case .levelStarting:
            return "Competition Level Starting"
        case .allianceSelection:
            return "Alliance Selection"
        case .awards:
            return "Awards Posted"
        case .mediaPosted:
            return "Media Posted"
        case .districtPointsUpdated:
            return "District Points Updated"
        case .scheduleUpdated:
            return "Event Schedule Updated"
        case .finalResults:
            return "Final Results"
        case .matchVideo:
            return "Match Video Added"
        case .eventMatchVideo:
            return "Match Video Added"
        default:
            return "" // These shouldn't render
        }
    }
}
struct MyTBASubscriptionsResponse: MyTBAResponse, Codable {
    var subscriptions: [MyTBASubscription]?
}
public struct MyTBASubscription: MyTBAModel, Equatable, Codable {
    public init(modelKey: String, modelType: MyTBAModelType, notifications: [NotificationType]) {
        self.modelKey = modelKey
        self.modelType = modelType
        self.notifications = notifications
    }
    public static var arrayKey: String {
        return "subscriptions"
    }
    public var modelKey: String
    public var modelType: MyTBAModelType
    public var notifications: [NotificationType]
    public static var fetch: (MyTBA) -> (@escaping ([MyTBAModel]?, Error?) -> Void) -> MyTBAOperation = MyTBA.fetchSubscriptions
}
extension MyTBA {
    public func fetchSubscriptions(_ completion: @escaping (_ subscriptions: [MyTBASubscription]?, _ error: Error?) -> Void) -> MyTBAOperation {
        let method = "\(MyTBASubscription.arrayKey)/list"
        return callApi(method: method, completion: { (favoritesResponse: MyTBASubscriptionsResponse?, error) in
            completion(favoritesResponse?.subscriptions, error)
        })
    }
}
 | 
	mit | 
| 
	witekbobrowski/Stanford-CS193p-Winter-2017 | 
	Smashtag/Smashtag/TwitterUser.swift | 
	1 | 
	1039 | 
	//
//  TwitterUser.swift
//  Smashtag
//
//  Created by Witek on 14/07/2017.
//  Copyright © 2017 Witek Bobrowski. All rights reserved.
//
import UIKit
import CoreData
import Twitter
class TwitterUser: NSManagedObject {
    class func findOrCreateTwitterUser(matching twitterInfo: Twitter.User, in context: NSManagedObjectContext) throws -> TwitterUser {
        
        let request: NSFetchRequest<TwitterUser> = TwitterUser.fetchRequest()
        request.predicate = NSPredicate(format: "handle = %@", twitterInfo.screenName)
        do {
            let matches = try context.fetch(request)
            if matches.count > 0 {
                assert(matches.count == 1, "TwitterUser.findOrCreateTwitterUser -- database inconsistency")
                return matches[0]
            }
        } catch {
            throw error
        }
        
        let twitterUser = TwitterUser(context: context)
        twitterUser.handle = twitterInfo.screenName
        twitterUser.name = twitterInfo.name
        return twitterUser
    }
}
 | 
	mit | 
| 
	quran/quran-ios | 
	Sources/Utilities/Extensions/Sequence+Extension.swift | 
	1 | 
	1427 | 
	//
//  Sequence+Extension.swift
//  Quran
//
//  Created by Mohamed Afifi on 2/19/17.
//
//  Quran for iOS is a Quran reading application for iOS.
//  Copyright (C) 2017  Quran.com
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
import Foundation
public extension Sequence {
    func flatGroup<U: Hashable>(by key: (Iterator.Element) -> U) -> [U: Iterator.Element] {
        var categories: [U: Iterator.Element] = [:]
        for element in self {
            let key = key(element)
            categories[key] = element
        }
        return categories
    }
}
extension Sequence where Iterator.Element: Hashable {
    public func orderedUnique() -> [Iterator.Element] {
        var buffer: [Iterator.Element] = []
        var added: Set<Iterator.Element> = []
        for elem in self {
            if !added.contains(elem) {
                buffer.append(elem)
                added.insert(elem)
            }
        }
        return buffer
    }
}
 | 
	apache-2.0 | 
| 
	SomeSimpleSolutions/MemorizeItForever | 
	MemorizeItForever/MemorizeItForever/VisualElements/MITextView.swift | 
	1 | 
	1000 | 
	//
//  MITextView.swift
//  MemorizeItForever
//
//  Created by Hadi Zamani on 11/8/16.
//  Copyright © 2016 SomeSimpleSolutions. All rights reserved.
//
import UIKit
final class MITextView: UITextView, ValidatableProtocol {
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        initialize()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initialize()
    }
    
    private func initialize(){
        self.translatesAutoresizingMaskIntoConstraints = false
        self.layer.cornerRadius = 18.0
        self.text = " "
        addBorder()
    }
    
    func applyError(){
        self.layer.borderColor = UIColor.red.cgColor
        self.layer.borderWidth = 3.0
    }
    func clearError(){
        addBorder()
    }
    
    private func addBorder(){
        self.layer.borderColor = UIColor.lightGray.cgColor
        self.layer.borderWidth = 1.0
    }
}
 | 
	mit | 
| 
	meismyles/SwiftWebVC | 
	SwiftWebVC/SwiftWebVC.swift | 
	1 | 
	14962 | 
	//
//  SwiftWebVC.swift
//
//  Created by Myles Ringle on 24/06/2015.
//  Transcribed from code used in SVWebViewController.
//  Copyright (c) 2015 Myles Ringle & Sam Vermette. All rights reserved.
//
import WebKit
public protocol SwiftWebVCDelegate: class {
    func didStartLoading()
    func didFinishLoading(success: Bool)
}
public class SwiftWebVC: UIViewController {
    
    public weak var delegate: SwiftWebVCDelegate?
    var storedStatusColor: UIBarStyle?
    var buttonColor: UIColor? = nil
    var titleColor: UIColor? = nil
    var closing: Bool! = false
    
    lazy var backBarButtonItem: UIBarButtonItem =  {
        var tempBackBarButtonItem = UIBarButtonItem(image: SwiftWebVC.bundledImage(named: "SwiftWebVCBack"),
                                                    style: UIBarButtonItemStyle.plain,
                                                    target: self,
                                                    action: #selector(SwiftWebVC.goBackTapped(_:)))
        tempBackBarButtonItem.width = 18.0
        tempBackBarButtonItem.tintColor = self.buttonColor
        return tempBackBarButtonItem
    }()
    
    lazy var forwardBarButtonItem: UIBarButtonItem =  {
        var tempForwardBarButtonItem = UIBarButtonItem(image: SwiftWebVC.bundledImage(named: "SwiftWebVCNext"),
                                                       style: UIBarButtonItemStyle.plain,
                                                       target: self,
                                                       action: #selector(SwiftWebVC.goForwardTapped(_:)))
        tempForwardBarButtonItem.width = 18.0
        tempForwardBarButtonItem.tintColor = self.buttonColor
        return tempForwardBarButtonItem
    }()
    
    lazy var refreshBarButtonItem: UIBarButtonItem = {
        var tempRefreshBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh,
                                                       target: self,
                                                       action: #selector(SwiftWebVC.reloadTapped(_:)))
        tempRefreshBarButtonItem.tintColor = self.buttonColor
        return tempRefreshBarButtonItem
    }()
    
    lazy var stopBarButtonItem: UIBarButtonItem = {
        var tempStopBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.stop,
                                                    target: self,
                                                    action: #selector(SwiftWebVC.stopTapped(_:)))
        tempStopBarButtonItem.tintColor = self.buttonColor
        return tempStopBarButtonItem
    }()
    
    lazy var actionBarButtonItem: UIBarButtonItem = {
        var tempActionBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action,
                                                      target: self,
                                                      action: #selector(SwiftWebVC.actionButtonTapped(_:)))
        tempActionBarButtonItem.tintColor = self.buttonColor
        return tempActionBarButtonItem
    }()
    
    
    lazy var webView: WKWebView = {
        var tempWebView = WKWebView(frame: UIScreen.main.bounds)
        tempWebView.uiDelegate = self
        tempWebView.navigationDelegate = self
        return tempWebView;
    }()
    
    var request: URLRequest!
    
    var navBarTitle: UILabel!
    
    var sharingEnabled = true
    
    ////////////////////////////////////////////////
    
    deinit {
        webView.stopLoading()
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        webView.uiDelegate = nil;
        webView.navigationDelegate = nil;
    }
    
    public convenience init(urlString: String, sharingEnabled: Bool = true) {
        var urlString = urlString
        if !urlString.hasPrefix("https://") && !urlString.hasPrefix("http://") {
            urlString = "https://"+urlString
        }
        self.init(pageURL: URL(string: urlString)!, sharingEnabled: sharingEnabled)
    }
    
    public convenience init(pageURL: URL, sharingEnabled: Bool = true) {
        self.init(aRequest: URLRequest(url: pageURL), sharingEnabled: sharingEnabled)
    }
    
    public convenience init(aRequest: URLRequest, sharingEnabled: Bool = true) {
        self.init()
        self.sharingEnabled = sharingEnabled
        self.request = aRequest
    }
    
    func loadRequest(_ request: URLRequest) {
        webView.load(request)
    }
    
    ////////////////////////////////////////////////
    // View Lifecycle
    
    override public func loadView() {
        view = webView
        loadRequest(request)
    }
    
    override public func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override public func viewWillAppear(_ animated: Bool) {
        assert(self.navigationController != nil, "SVWebViewController needs to be contained in a UINavigationController. If you are presenting SVWebViewController modally, use SVModalWebViewController instead.")
        
        updateToolbarItems()
        navBarTitle = UILabel()
        navBarTitle.backgroundColor = UIColor.clear
        if presentingViewController == nil {
            if let titleAttributes = navigationController!.navigationBar.titleTextAttributes {
                navBarTitle.textColor = titleAttributes[.foregroundColor] as? UIColor
            }
        }
        else {
            navBarTitle.textColor = self.titleColor
        }
        navBarTitle.shadowOffset = CGSize(width: 0, height: 1);
        navBarTitle.font = UIFont(name: "HelveticaNeue-Medium", size: 17.0)
        navBarTitle.textAlignment = .center
        navigationItem.titleView = navBarTitle;
        
        super.viewWillAppear(true)
        
        if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone) {
            self.navigationController?.setToolbarHidden(false, animated: false)
        }
        else if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad) {
            self.navigationController?.setToolbarHidden(true, animated: true)
        }
    }
    
    override public func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
        
        if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone) {
            self.navigationController?.setToolbarHidden(true, animated: true)
        }
    }
    
    override public func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
    }
    
    ////////////////////////////////////////////////
    // Toolbar
    
    func updateToolbarItems() {
        backBarButtonItem.isEnabled = webView.canGoBack
        forwardBarButtonItem.isEnabled = webView.canGoForward
        
        let refreshStopBarButtonItem: UIBarButtonItem = webView.isLoading ? stopBarButtonItem : refreshBarButtonItem
        
        let fixedSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
        let flexibleSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        
        if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad) {
            
            let toolbarWidth: CGFloat = 250.0
            fixedSpace.width = 35.0
            
            let items: NSArray = sharingEnabled ? [fixedSpace, refreshStopBarButtonItem, fixedSpace, backBarButtonItem, fixedSpace, forwardBarButtonItem, fixedSpace, actionBarButtonItem] : [fixedSpace, refreshStopBarButtonItem, fixedSpace, backBarButtonItem, fixedSpace, forwardBarButtonItem]
            
            let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: toolbarWidth, height: 44.0))
            if !closing {
                toolbar.items = items as? [UIBarButtonItem]
                if presentingViewController == nil {
                    toolbar.barTintColor = navigationController!.navigationBar.barTintColor
                }
                else {
                    toolbar.barStyle = navigationController!.navigationBar.barStyle
                }
                toolbar.tintColor = navigationController!.navigationBar.tintColor
            }
            navigationItem.rightBarButtonItems = items.reverseObjectEnumerator().allObjects as? [UIBarButtonItem]
            
        }
        else {
            let items: NSArray = sharingEnabled ? [fixedSpace, backBarButtonItem, flexibleSpace, forwardBarButtonItem, flexibleSpace, refreshStopBarButtonItem, flexibleSpace, actionBarButtonItem, fixedSpace] : [fixedSpace, backBarButtonItem, flexibleSpace, forwardBarButtonItem, flexibleSpace, refreshStopBarButtonItem, fixedSpace]
            
            if let navigationController = navigationController, !closing {
                if presentingViewController == nil {
                    navigationController.toolbar.barTintColor = navigationController.navigationBar.barTintColor
                }
                else {
                    navigationController.toolbar.barStyle = navigationController.navigationBar.barStyle
                }
                navigationController.toolbar.tintColor = navigationController.navigationBar.tintColor
                toolbarItems = items as? [UIBarButtonItem]
            }
        }
    }
    
    
    ////////////////////////////////////////////////
    // Target Actions
    
    @objc func goBackTapped(_ sender: UIBarButtonItem) {
        webView.goBack()
    }
    
    @objc func goForwardTapped(_ sender: UIBarButtonItem) {
        webView.goForward()
    }
    
    @objc func reloadTapped(_ sender: UIBarButtonItem) {
        webView.reload()
    }
    
    @objc func stopTapped(_ sender: UIBarButtonItem) {
        webView.stopLoading()
        updateToolbarItems()
    }
    
    @objc func actionButtonTapped(_ sender: AnyObject) {
        
        if let url: URL = ((webView.url != nil) ? webView.url : request.url) {
            let activities: NSArray = [SwiftWebVCActivitySafari(), SwiftWebVCActivityChrome()]
            
            if url.absoluteString.hasPrefix("file:///") {
                let dc: UIDocumentInteractionController = UIDocumentInteractionController(url: url)
                dc.presentOptionsMenu(from: view.bounds, in: view, animated: true)
            }
            else {
                let activityController: UIActivityViewController = UIActivityViewController(activityItems: [url], applicationActivities: activities as? [UIActivity])
                
                if floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1 && UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad {
                    let ctrl: UIPopoverPresentationController = activityController.popoverPresentationController!
                    ctrl.sourceView = view
                    ctrl.barButtonItem = sender as? UIBarButtonItem
                }
                
                present(activityController, animated: true, completion: nil)
            }
        }
    }
    
    ////////////////////////////////////////////////
    
    @objc func doneButtonTapped() {
        closing = true
        UINavigationBar.appearance().barStyle = storedStatusColor!
        self.dismiss(animated: true, completion: nil)
    }
    // MARK: - Class Methods
    /// Helper function to get image within SwiftWebVCResources bundle
    ///
    /// - parameter named: The name of the image in the SwiftWebVCResources bundle
    class func bundledImage(named: String) -> UIImage? {
        let image = UIImage(named: named)
        if image == nil {
            return UIImage(named: named, in: Bundle(for: SwiftWebVC.classForCoder()), compatibleWith: nil)
        } // Replace MyBasePodClass with yours
        return image
    }
    
}
extension SwiftWebVC: WKUIDelegate {
    
    // Add any desired WKUIDelegate methods here: https://developer.apple.com/reference/webkit/wkuidelegate
    
}
extension SwiftWebVC: WKNavigationDelegate {
    
    public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        self.delegate?.didStartLoading()
        UIApplication.shared.isNetworkActivityIndicatorVisible = true
        updateToolbarItems()
    }
    
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.delegate?.didFinishLoading(success: true)
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        
        webView.evaluateJavaScript("document.title", completionHandler: {(response, error) in
            self.navBarTitle.text = response as! String?
            self.navBarTitle.sizeToFit()
            self.updateToolbarItems()
        })
        
    }
    
    public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        self.delegate?.didFinishLoading(success: false)
        UIApplication.shared.isNetworkActivityIndicatorVisible = false
        updateToolbarItems()
    }
    
    public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        let url = navigationAction.request.url
        
        let hostAddress = navigationAction.request.url?.host
        
        if (navigationAction.targetFrame == nil) {
            if UIApplication.shared.canOpenURL(url!) {
                UIApplication.shared.openURL(url!)
            }
        }
        
        // To connnect app store
        if hostAddress == "itunes.apple.com" {
            if UIApplication.shared.canOpenURL(navigationAction.request.url!) {
                UIApplication.shared.openURL(navigationAction.request.url!)
                decisionHandler(.cancel)
                return
            }
        }
        
        let url_elements = url!.absoluteString.components(separatedBy: ":")
        
        switch url_elements[0] {
        case "tel":
            openCustomApp(urlScheme: "telprompt://", additional_info: url_elements[1])
            decisionHandler(.cancel)
            
        case "sms":
            openCustomApp(urlScheme: "sms://", additional_info: url_elements[1])
            decisionHandler(.cancel)
            
        case "mailto":
            openCustomApp(urlScheme: "mailto://", additional_info: url_elements[1])
            decisionHandler(.cancel)
            
        default:
            //print("Default")
            break
        }
        
        decisionHandler(.allow)
        
    }
    
    func openCustomApp(urlScheme: String, additional_info:String){
        
        if let requestUrl: URL = URL(string:"\(urlScheme)"+"\(additional_info)") {
            let application:UIApplication = UIApplication.shared
            if application.canOpenURL(requestUrl) {
                application.openURL(requestUrl)
            }
        }
    }
}
 | 
	mit | 
| 
	Donkey-Tao/SinaWeibo | 
	SinaWeibo/SinaWeibo/Classes/Main/Visitor/TFVisitorView.swift | 
	1 | 
	1546 | 
	//
//  TFVisitorView.swift
//  SinaWeibo
//
//  Created by Donkey-Tao on 2016/9/27.
//  Copyright © 2016年 http://taofei.me All rights reserved.
//
import UIKit
class TFVisitorView: UIView {
    //MARK:- 控件的属性
    @IBOutlet weak var rotationView: UIImageView!
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var tipsLabel: UILabel!
    
    @IBOutlet weak var loginBtn: UIButton!
    @IBOutlet weak var registerBtn: UIButton!
    //MARK:- 自定义函数
    
    ///设置访客视图
    func setupVisitorViewInfo(iconName : String ,tip :String){
    
        iconView.image = UIImage(named: iconName)
        tipsLabel.text = tip
        rotationView.isHidden = true
    }
    
    ///添加rotationView的动画
    func addRotationViewAnimation(){
        //1.创建动画:CABasicAnimation或者CAKeyframeAnimation来实现
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        //2.设置动画的属性
        rotationAnimation.fromValue = 0
        rotationAnimation.toValue = M_PI * 2
        rotationAnimation.repeatCount = MAXFLOAT
        rotationAnimation.duration = 5
        rotationAnimation.isRemovedOnCompletion = false
        //3.将动画添加到layer中
        rotationView.layer.add(rotationAnimation, forKey: nil)    
    }
    
    //MARK:- 提供快速通过Xib创建的类方法
    class func TFVisitorView() -> TFVisitorView {
        return Bundle.main.loadNibNamed("TFVisitorView", owner: nil, options: nil)?.first as! TFVisitorView
    }
}
 | 
	mit | 
| 
	xedin/swift | 
	test/Sema/enum_raw_representable.swift | 
	7 | 
	6632 | 
	// RUN: %target-typecheck-verify-swift
enum Foo : Int {
  case a, b, c
}
var raw1: Int = Foo.a.rawValue
var raw2: Foo.RawValue = raw1
var cooked1: Foo? = Foo(rawValue: 0)
var cooked2: Foo? = Foo(rawValue: 22)
enum Bar : Double {
  case a, b, c
}
func localEnum() -> Int {
  enum LocalEnum : Int {
    case a, b, c
  }
  return LocalEnum.a.rawValue
}
enum MembersReferenceRawType : Int {
  case a, b, c
  init?(rawValue: Int) {
    self = MembersReferenceRawType(rawValue: rawValue)!
  }
  func successor() -> MembersReferenceRawType {
    return MembersReferenceRawType(rawValue: rawValue + 1)!
  }
}
func serialize<T : RawRepresentable>(_ values: [T]) -> [T.RawValue] {
  return values.map { $0.rawValue }
}
func deserialize<T : RawRepresentable>(_ serialized: [T.RawValue]) -> [T] {
  return serialized.map { T(rawValue: $0)! }
}
var ints: [Int] = serialize([Foo.a, .b, .c])
var doubles: [Double] = serialize([Bar.a, .b, .c])
var foos: [Foo] = deserialize([1, 2, 3])
var bars: [Bar] = deserialize([1.2, 3.4, 5.6])
// Infer RawValue from witnesses.
enum Color : Int {
  case red
  case blue
  init?(rawValue: Double) {
    return nil
  }
  var rawValue: Double {
    return 1.0
  }
}
var colorRaw: Color.RawValue = 7.5
// Mismatched case types
enum BadPlain : UInt { // expected-error {{'BadPlain' declares raw type 'UInt', but does not conform to RawRepresentable and conformance could not be synthesized}}
    case a = "hello"   // expected-error {{cannot convert value of type 'String' to raw type 'UInt'}}
}
// Recursive diagnostics issue in tryRawRepresentableFixIts()
class Outer {
  // The setup is that we have to trigger the conformance check
  // while diagnosing the conversion here. For the purposes of
  // the test I'm putting everything inside a class in the right
  // order, but the problem can trigger with a multi-file
  // scenario too.
  let a: Int = E.a // expected-error {{cannot convert value of type 'Outer.E' to specified type 'Int'}}
  enum E : Array<Int> { // expected-error {{raw type 'Array<Int>' is not expressible by a string, integer, or floating-point literal}}
    case a
  }
}
// rdar://problem/32431736 - Conversion fix-it from String to String raw value enum can't look through optionals
func rdar32431736() {
  enum E : String {
    case A = "A"
    case B = "B"
  }
  let items1: [String] = ["A", "a"]
  let items2: [String]? = ["A"]
  let myE1: E = items1.first
  // expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}}
  // expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: }} {{29-29=!)}}
  let myE2: E = items2?.first
  // expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}}
  // expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: (}} {{30-30=)!)}}
}
// rdar://problem/32431165 - improve diagnostic for raw representable argument mismatch
enum E_32431165 : String {
  case foo = "foo"
  case bar = "bar" // expected-note {{'bar' declared here}}
}
func rdar32431165_1(_: E_32431165) {}
func rdar32431165_1(_: Int) {}
func rdar32431165_1(_: Int, _: E_32431165) {}
rdar32431165_1(E_32431165.baz)
// expected-error@-1 {{type 'E_32431165' has no member 'baz'; did you mean 'bar'?}}
rdar32431165_1(.baz)
// expected-error@-1 {{reference to member 'baz' cannot be resolved without a contextual type}}
rdar32431165_1("")
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{16-16=E_32431165(rawValue: }} {{18-18=)}}
rdar32431165_1(42, "")
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{20-20=E_32431165(rawValue: }} {{22-22=)}}
func rdar32431165_2(_: String) {}
func rdar32431165_2(_: Int) {}
func rdar32431165_2(_: Int, _: String) {}
rdar32431165_2(E_32431165.bar)
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{16-16=}} {{30-30=.rawValue}}
rdar32431165_2(42, E_32431165.bar)
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{20-20=}} {{34-34=.rawValue}}
E_32431165.bar == "bar"
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{1-1=}} {{15-15=.rawValue}}
"bar" == E_32431165.bar
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{10-10=}} {{24-24=.rawValue}}
func rdar32432253(_ condition: Bool = false) {
  let choice: E_32431165 = condition ? .foo : .bar
  let _ = choice == "bar"
  // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{11-11=}} {{17-17=.rawValue}}
}
func sr8150_helper1(_: Int) {}
func sr8150_helper1(_: Double) {}
func sr8150_helper2(_: Double) {}
func sr8150_helper2(_: Int) {}
func sr8150_helper3(_: Foo) {}
func sr8150_helper3(_: Bar) {}
func sr8150_helper4(_: Bar) {}
func sr8150_helper4(_: Foo) {}
func sr8150(bar: Bar) {
  sr8150_helper1(bar)
  // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
  sr8150_helper2(bar)
  // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
  sr8150_helper3(0.0)
  // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}}
  sr8150_helper4(0.0)
  // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}}
}
class SR8150Box {
  var bar: Bar
  init(bar: Bar) { self.bar = bar }
}
// Bonus problem with mutable values being passed.
func sr8150_mutable(obj: SR8150Box) {
  sr8150_helper1(obj.bar)
  // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{25-25=.rawValue}}
  var bar = obj.bar
  sr8150_helper1(bar)
  // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
}
struct NotEquatable { }
enum ArrayOfNewEquatable : Array<NotEquatable> { }
// expected-error@-1{{raw type 'Array<NotEquatable>' is not expressible by a string, integer, or floating-point literal}}
// expected-error@-2{{'ArrayOfNewEquatable' declares raw type 'Array<NotEquatable>', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-3{{RawRepresentable conformance cannot be synthesized because raw type 'Array<NotEquatable>' is not Equatable}}
 | 
	apache-2.0 | 
| 
	xuzhuoxi/SearchKit | 
	Source/cs/cache/valuecoding/WubiWordStrategyImpl.swift | 
	1 | 
	1937 | 
	//
//  WubiWordStrategyImpl.swift
//  SearchKit
//
//  Created by 许灼溪 on 15/12/19.
//
//
import Foundation
/**
 *
 * @author xuzhuoxi
 *
 */
class WubiWordStrategyImpl: AbstractWubiStrategy, ValueCodingStrategyProtocol, ReflectionProtocol {
    
    final func getSimplifyValue(_ value: String) ->String {
        return value
    }
    
    final func getDimensionKeys(_ simplifyValue: String) ->[String] {
        return abstractGetDimensionKeys(simplifyValue);
    }
    
    final func filter(_ input: String) -> String {
        return wubiFilter(input);
    }
    
    /**
     * 如果输入中包含已编码的中文,返回对应第一个中文的编码<br>
     * 否则截取前4位拼音字符作为返回
     */
    final func translate(_ filteredInput: String) ->[String] {
        if ChineseUtils.hasChinese(filteredInput) {
            let wordWubiMap = CachePool.instance.getCache(CacheNames.WUBI_WORD) as! CharacterLibraryProtocol
            for key in filteredInput.characters {
                if ChineseUtils.isChinese(key) { // 是字典中的汉字,返回编码
                    if wordWubiMap.isKey(key) {
                        return wordWubiMap.getValues(key)!
                    }
                }
            }
        }
        return [filteredInput.substring(to: filteredInput.characters.index(filteredInput.startIndex, offsetBy: 4))]
    }
    
    /**
     * 简化编码的计算过程:<br>
     * 分别截取从前[1-length]位作为dimensionKeys<br>
     */
    override final func computeDimensionKeys(_ simplifyValue: String) ->[String] {
        var rs = [String]()
        for i in 0 ..< simplifyValue.length {
            rs.append(simplifyValue.substring(to: simplifyValue.characters.index(simplifyValue.startIndex, offsetBy: i+1)))
        }
        return rs
    }
    
    static func newInstance() -> ReflectionProtocol {
        return WubiWordStrategyImpl()
    }
}
 | 
	mit | 
| 
	uber/rides-ios-sdk | 
	source/UberCore/Authentication/Authenticators/RidesAuthenticationDeeplink.swift | 
	1 | 
	1923 | 
	//
//  RidesAuthenticationDeeplink.swift
//  UberRides
//
//  Copyright © 2018 Uber Technologies, Inc. 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 Foundation
/**
 *  A Deeplinking object for authenticating a user via the native Uber rides app
 */
@objc(UBSDKRidesAuthenticationDeeplink) public class RidesAuthenticationDeeplink: BaseDeeplink {
    /**
     Initializes an Authentication Deeplink to request the provided scopes
     - parameter scopes: An array of UberScopes you would like to request
     - returns: An initialized AuthenticationDeeplink
     */
    @objc public init(scopes: [UberScope]) {
        let queryItems = AuthenticationURLUtility.buildQueryParameters(scopes)
        let scheme = "uberauth"
        let domain = "connect"
        super.init(scheme: scheme, host: domain, path: "", queryItems: queryItems)!
    }
}
 | 
	mit | 
| 
	zhiquan911/chance_btc_wallet | 
	chance_btc_wallet/chance_btc_wallet/extension/UILabel+extension.swift | 
	1 | 
	1111 | 
	//
//  UILabel+extension.swift
//  Chance_wallet
//
//  Created by Chance on 15/12/6.
//  Copyright © 2015年 Chance. All rights reserved.
//
import Foundation
extension UILabel {
    
    public func setDecimalStr(
        _ number: String,
        color: UIColor?
        ) {
            self.text = number
            if number.range(of: ".") != nil && color != nil {
                let colorDict = [NSAttributedStringKey.foregroundColor: color!]
                let re_range = number.range(of: ".")!
                let index: Int = number.distance(from: number.startIndex, to: re_range.lowerBound)
                let last = number.length
                let length = last - index
                let newRange = NSMakeRange(index, length)
                let attributedStr = NSMutableAttributedString(string: number)
                
                if newRange.location + newRange.length <= attributedStr.length  {
                    attributedStr.addAttributes(colorDict, range: newRange)
                }
                
                self.attributedText = attributedStr;
            }
    }
}
 | 
	mit | 
| 
	kstaring/swift | 
	validation-test/compiler_crashers_fixed/25720-swift-constraints-constraintsystem-simplifyconstraint.swift | 
	11 | 
	496 | 
	// 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
// RUN: not %target-swift-frontend %s -parse
let a{
struct B
class B{func c<T{{
{
}
}
var _=c<T>{
}protocol g{
class a
class c<T where B:A class a:c
 | 
	apache-2.0 | 
| 
	wikimedia/wikipedia-ios | 
	Wikipedia/Code/AbuseFilterAlertView.swift | 
	1 | 
	3668 | 
	enum AbuseFilterAlertType {
    case warning
    case disallow
    func image() -> UIImage? {
        switch self {
        case .warning:
            return #imageLiteral(resourceName: "abuse-filter-flag")
        case .disallow:
            return #imageLiteral(resourceName: "abuse-filter-alert")
        }
    }
}
class AbuseFilterAlertView: UIView, Themeable {
    @IBOutlet private var iconImageView: UIImageView!
    @IBOutlet private var titleLabel: UILabel!
    @IBOutlet private var subtitleLabel: UILabel!
    @IBOutlet private var detailsLabel1: UILabel!
    @IBOutlet private var detailsLabel2: UILabel!
    @IBOutlet private var detailsLabel3: UILabel!
    @IBOutlet private var detailsLabel4: UILabel!
    @IBOutlet private var detailsLabel5: UILabel!
    public var theme: Theme = .standard
    public var type: AbuseFilterAlertType = .disallow {
        didSet {
            iconImageView.image = type.image()
            configureLabels(for: type)
        }
    }
    private func configureLabels(for type: AbuseFilterAlertType) {
        switch type {
        case .disallow:
            titleLabel.text = WMFLocalizedString("abuse-filter-disallow-heading", value: "You cannot publish this edit", comment: "Header text for disallowed edit warning.")
            subtitleLabel.text = nil
            detailsLabel1.text = WMFLocalizedString("abuse-filter-disallow-unconstructive", value: "An automated filter has identified this edit as potentially unconstructive or as a vandalism attempt. Please go back and change your edit.", comment: "Label text for unconstructive edit description")
            detailsLabel2.text = nil
            detailsLabel3.text = nil
            detailsLabel4.text = nil
            detailsLabel5.text = nil
        case .warning:
            titleLabel.text = WMFLocalizedString("abuse-filter-warning-heading", value: "This looks like an unconstructive edit, are you sure you want to publish it?", comment: "Header text for unconstructive edit warning")
            subtitleLabel.text = WMFLocalizedString("abuse-filter-warning-subheading", value: "Your edit may contain:", comment: "Subheading text for potentially unconstructive edit warning")
            detailsLabel1.text = WMFLocalizedString("abuse-filter-warning-caps", value: "All caps text", comment: "Label text for typing in all capitals")
            detailsLabel2.text = WMFLocalizedString("abuse-filter-warning-blanking", value: "Deleting sections or full articles", comment: "Label text for blanking sections or articles")
            detailsLabel3.text = WMFLocalizedString("abuse-filter-warning-spam", value: "Adding spam to articles", comment: "Label text for adding spam to articles")
            detailsLabel4.text = WMFLocalizedString("abuse-filter-warning-irrelevant", value: "Irrelevant external links or images", comment: "Label text for irrelevant external links and images")
            detailsLabel5.text = WMFLocalizedString("abuse-filter-warning-repeat", value: "Repeating characters", comment: "Label text for repeating characters")
        }
    }
    
    func apply(theme: Theme) {
        self.theme = theme
        backgroundColor = theme.colors.paperBackground
        titleLabel.textColor = (type == .disallow) ? theme.colors.error : theme.colors.warning
        subtitleLabel.textColor = theme.colors.secondaryText
        detailsLabel1.textColor = theme.colors.secondaryText
        detailsLabel2.textColor = theme.colors.secondaryText
        detailsLabel3.textColor = theme.colors.secondaryText
        detailsLabel4.textColor = theme.colors.secondaryText
        detailsLabel5.textColor = theme.colors.secondaryText
    }
}
 | 
	mit | 
| 
	fgengine/quickly | 
	Quickly/ViewControllers/Hamburger/Animation/QHamburgerViewControllerInteractiveAnimation.swift | 
	1 | 
	10450 | 
	//
//  Quickly
//
public final class QHamburgerViewControllerInteractiveAnimation : IQHamburgerViewControllerInteractiveAnimation {
    
    public var contentView: UIView!
    public var currentState: QHamburgerViewControllerState
    public var targetState: QHamburgerViewControllerState
    public var contentViewController: IQHamburgerViewController!
    public var contentShadow: QViewShadow
    public var contentBeginFrame: CGRect!
    public var contentEndFrame: CGRect!
    public var leftSize: CGFloat
    public var leftViewController: IQHamburgerViewController?
    public var leftBeginFrame: CGRect!
    public var leftEndFrame: CGRect!
    public var rightSize: CGFloat
    public var rightViewController: IQHamburgerViewController?
    public var rightBeginFrame: CGRect!
    public var rightEndFrame: CGRect!
    public var position: CGPoint
    public var deltaPosition: CGFloat
    public var velocity: CGPoint
    public var acceleration: CGFloat
    public var finishDistanceRate: CGFloat
    public var ease: IQAnimationEase
    public var canFinish: Bool
    
    public init(
        contentShadow: QViewShadow = QViewShadow(color: UIColor.black, opacity: 0.45, radius: 6, offset: CGSize.zero),
        leftSize: CGFloat = UIScreen.main.bounds.width * 0.6,
        rightSize: CGFloat = UIScreen.main.bounds.width * 0.6,
        acceleration: CGFloat = 1200,
        finishDistanceRate: CGFloat = 0.4,
        ease: IQAnimationEase = QAnimationEaseQuadraticOut()
    ) {
        self.currentState = .idle
        self.targetState = .idle
        self.contentShadow = contentShadow
        self.leftSize = leftSize
        self.rightSize = rightSize
        self.position = CGPoint.zero
        self.deltaPosition = 0
        self.velocity = CGPoint.zero
        self.acceleration = acceleration
        self.finishDistanceRate = finishDistanceRate
        self.ease = ease
        self.canFinish = false
    }
    
    public func prepare(
        contentView: UIView,
        currentState: QHamburgerViewControllerState,
        targetState: QHamburgerViewControllerState,
        contentViewController: IQHamburgerViewController,
        leftViewController: IQHamburgerViewController?,
        rightViewController: IQHamburgerViewController?,
        position: CGPoint,
        velocity: CGPoint
    ) {
        self.contentView = contentView
        self.currentState = currentState
        self.targetState = targetState
        self.contentViewController = contentViewController
        self.contentBeginFrame = self._contentFrame(contentView: contentView, state: currentState)
        self.contentEndFrame = self._contentFrame(contentView: contentView, state: targetState)
        self.leftViewController = leftViewController
        self.leftBeginFrame = self._leftFrame(contentView: contentView, state: currentState)
        self.leftEndFrame = self._leftFrame(contentView: contentView, state: targetState)
        self.rightViewController = rightViewController
        self.rightBeginFrame = self._rightFrame(contentView: contentView, state: currentState)
        self.rightEndFrame = self._rightFrame(contentView: contentView, state: targetState)
        self.position = position
        self.velocity = velocity
        
        self.contentView.bringSubviewToFront(self.contentViewController.view)
        self.contentViewController.view.frame = self.contentBeginFrame
        self.contentViewController.view.shadow = self.contentShadow
        if let vc = self.leftViewController {
            vc.view.frame = self.leftBeginFrame
            if currentState == .left { vc.prepareInteractiveDismiss() }
            if targetState == .left { vc.prepareInteractivePresent() }
        }
        if let vc = self.rightViewController {
            vc.view.frame = self.rightBeginFrame
            if currentState == .right { vc.prepareInteractiveDismiss() }
            if targetState == .right { vc.prepareInteractivePresent() }
        }
    }
    
    public func update(position: CGPoint, velocity: CGPoint) {
        var delta: CGFloat = position.x - self.position.x
        switch self.currentState {
        case .idle:
            switch self.targetState {
            case .idle, .left: break
            case .right: delta = -delta
            }
        case .left:
            switch self.targetState {
            case .idle, .right: delta = -delta
            case .left: break
            }
        case .right: break
        }
        let distance = self._distance()
        self.deltaPosition = self.ease.lerp(max(0, min(delta, distance)), from: 0, to: distance)
        let progress = self.deltaPosition / distance
        self.contentViewController.view.frame = self.contentBeginFrame.lerp(self.contentEndFrame, progress: progress)
        self.leftViewController?.view.frame = self.leftBeginFrame.lerp(self.leftEndFrame, progress: progress)
        self.rightViewController?.view.frame = self.rightBeginFrame.lerp(self.rightEndFrame, progress: progress)
        self.canFinish = self.deltaPosition > (distance * self.finishDistanceRate)
    }
    
    public func finish(_ complete: @escaping (_ state: QHamburgerViewControllerState) -> Void) {
        let distance = self._distance()
        let duration = TimeInterval((distance - self.deltaPosition) / self.acceleration)
        UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
            self.contentViewController.view.frame = self.contentEndFrame
            self.leftViewController?.view.frame = self.leftEndFrame
            self.rightViewController?.view.frame = self.rightEndFrame
        }, completion: { [weak self] (completed: Bool) in
            guard let self = self else { return }
            self.contentViewController.view.frame = self.contentEndFrame
            self.contentViewController.view.shadow = self.targetState != .idle ? self.contentShadow : nil
            self.contentViewController = nil
            if let vc = self.leftViewController {
                vc.view.frame = self.leftEndFrame
                if self.currentState == .left { vc.finishInteractiveDismiss() }
                if self.targetState == .left { vc.finishInteractivePresent() }
                self.leftViewController = nil
            }
            if let vc = self.rightViewController {
                vc.view.frame = self.rightEndFrame
                if self.currentState == .left { vc.finishInteractiveDismiss() }
                if self.targetState == .left { vc.finishInteractivePresent() }
                self.rightViewController = nil
            }
            complete(self.targetState)
        })
    }
    
    public func cancel(_ complete: @escaping (_ state: QHamburgerViewControllerState) -> Void) {
        let duration = TimeInterval(self.deltaPosition / self.acceleration)
        UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: {
            self.contentViewController.view.frame = self.contentBeginFrame
            self.leftViewController?.view.frame = self.leftBeginFrame
            self.rightViewController?.view.frame = self.rightBeginFrame
        }, completion: { [weak self] (completed: Bool) in
            guard let self = self else { return }
            self.contentViewController.view.frame = self.contentBeginFrame
            self.contentViewController.view.shadow = self.currentState != .idle ? self.contentShadow : nil
            self.contentViewController = nil
            if let vc = self.leftViewController {
                vc.view.frame = self.leftBeginFrame
                if self.currentState == .left { vc.cancelInteractiveDismiss() }
                if self.targetState == .left { vc.cancelInteractivePresent() }
                self.leftViewController = nil
            }
            if let vc = self.rightViewController {
                vc.view.frame = self.rightBeginFrame
                if self.currentState == .left { vc.cancelInteractiveDismiss() }
                if self.targetState == .left { vc.cancelInteractivePresent() }
                self.rightViewController = nil
            }
            complete(self.currentState)
        })
    }
    
}
// MARK: Private
private extension QHamburgerViewControllerInteractiveAnimation {
    
    func _distance() -> CGFloat {
        switch self.currentState {
        case .idle:
            switch self.targetState {
            case .idle: return 0
            case .left: return self.leftSize
            case .right: return self.rightSize
            }
        case .left:
            switch self.targetState {
            case .idle: return self.leftSize
            case .left: return 0
            case .right: return self.leftSize + self.rightSize
            }
        case .right:
            switch self.targetState {
            case .idle: return self.rightSize
            case .left: return self.leftSize + self.rightSize
            case .right: return 0
            }
        }
    }
    
    func _contentFrame(contentView: UIView, state: QHamburgerViewControllerState) -> CGRect {
        let bounds = contentView.bounds
        switch state {
        case .idle: return bounds
        case .left: return CGRect(x: bounds.origin.x + self.leftSize, y: bounds.origin.y, width: bounds.width, height: bounds.height)
        case .right: return CGRect(x: bounds.origin.x - self.rightSize, y: bounds.origin.y, width: bounds.width, height: bounds.height)
        }
    }
    
    func _leftFrame(contentView: UIView, state: QHamburgerViewControllerState) -> CGRect {
        let bounds = contentView.bounds
        switch state {
        case .idle, .right: return CGRect(x: bounds.origin.x - self.leftSize, y: bounds.origin.y, width: self.leftSize, height: bounds.height)
        case .left: return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: self.leftSize, height: bounds.height)
        }
    }
    
    func _rightFrame(contentView: UIView, state: QHamburgerViewControllerState) -> CGRect {
        let bounds = contentView.bounds
        switch state {
        case .idle, .left: return CGRect(x: bounds.origin.x + bounds.width, y: bounds.origin.y, width: self.rightSize, height: bounds.height)
        case .right: return CGRect(x: (bounds.origin.x + bounds.width) - self.rightSize, y: bounds.origin.y, width: self.rightSize, height: bounds.height)
        }
    }
    
}
 | 
	mit | 
| 
	seanooi/DocuParse | 
	DocuParseTests/DocuParseTests.swift | 
	1 | 
	976 | 
	//
//  DocuParseTests.swift
//  DocuParseTests
//
//  Created by Sean Ooi on 12/4/15.
//  Copyright © 2015 Sean Ooi. All rights reserved.
//
import XCTest
@testable import DocuParse
class DocuParseTests: XCTestCase {
    
    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }
    
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    
    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }
    
    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock {
            // Put the code you want to measure the time of here.
        }
    }
    
}
 | 
	mit | 
| 
	AgaKhanFoundation/WCF-iOS | 
	Pods/Quick/Sources/Quick/Configuration/QCKConfiguration.swift | 
	3 | 
	7498 | 
	import Foundation
/**
    A closure that temporarily exposes a QCKConfiguration object within
    the scope of the closure.
*/
public typealias QuickConfigurer = (_ configuration: QCKConfiguration) -> Void
/**
    A closure that, given metadata about an example, returns a boolean value
    indicating whether that example should be run.
*/
public typealias ExampleFilter = (_ example: Example) -> Bool
/**
    A configuration encapsulates various options you can use
    to configure Quick's behavior.
*/
final public class QCKConfiguration: NSObject {
    internal let exampleHooks = ExampleHooks()
    internal let suiteHooks = SuiteHooks()
    internal var exclusionFilters: [ExampleFilter] = [
        { example in // swiftlint:disable:this opening_brace
            if let pending = example.filterFlags[Filter.pending] {
                return pending
            } else {
                return false
            }
        },
    ]
    internal var inclusionFilters: [ExampleFilter] = [
        { example in // swiftlint:disable:this opening_brace
            if let focused = example.filterFlags[Filter.focused] {
                return focused
            } else {
                return false
            }
        },
    ]
    /**
        Run all examples if none match the configured filters. True by default.
    */
    public var runAllWhenEverythingFiltered = true
    /**
        Registers an inclusion filter.
        All examples are filtered using all inclusion filters.
        The remaining examples are run. If no examples remain, all examples are run.
        - parameter filter: A filter that, given an example, returns a value indicating
                       whether that example should be included in the examples
                       that are run.
    */
    public func include(_ filter: @escaping ExampleFilter) {
        inclusionFilters.append(filter)
    }
    /**
        Registers an exclusion filter.
        All examples that remain after being filtered by the inclusion filters are
        then filtered via all exclusion filters.
        - parameter filter: A filter that, given an example, returns a value indicating
                       whether that example should be excluded from the examples
                       that are run.
    */
    public func exclude(_ filter: @escaping ExampleFilter) {
        exclusionFilters.append(filter)
    }
    /**
        Identical to Quick.QCKConfiguration.beforeEach, except the closure is
        provided with metadata on the example that the closure is being run
        prior to.
    */
#if canImport(Darwin)
    @objc(beforeEachWithMetadata:)
    public func beforeEach(_ closure: @escaping BeforeExampleWithMetadataClosure) {
        exampleHooks.appendBefore(closure)
    }
#else
    public func beforeEach(_ closure: @escaping BeforeExampleWithMetadataClosure) {
        exampleHooks.appendBefore(closure)
    }
#endif
    /**
        Like Quick.DSL.beforeEach, this configures Quick to execute the
        given closure before each example that is run. The closure
        passed to this method is executed before each example Quick runs,
        globally across the test suite. You may call this method multiple
        times across multiple +[QuickConfigure configure:] methods in order
        to define several closures to run before each example.
        Note that, since Quick makes no guarantee as to the order in which
        +[QuickConfiguration configure:] methods are evaluated, there is no
        guarantee as to the order in which beforeEach closures are evaluated
        either. Multiple beforeEach defined on a single configuration, however,
        will be executed in the order they're defined.
        - parameter closure: The closure to be executed before each example
                        in the test suite.
    */
    public func beforeEach(_ closure: @escaping BeforeExampleClosure) {
        exampleHooks.appendBefore(closure)
    }
    /**
        Identical to Quick.QCKConfiguration.afterEach, except the closure
        is provided with metadata on the example that the closure is being
        run after.
    */
#if canImport(Darwin)
    @objc(afterEachWithMetadata:)
    public func afterEach(_ closure: @escaping AfterExampleWithMetadataClosure) {
        exampleHooks.appendAfter(closure)
    }
#else
    public func afterEach(_ closure: @escaping AfterExampleWithMetadataClosure) {
        exampleHooks.appendAfter(closure)
    }
#endif
    /**
        Like Quick.DSL.afterEach, this configures Quick to execute the
        given closure after each example that is run. The closure
        passed to this method is executed after each example Quick runs,
        globally across the test suite. You may call this method multiple
        times across multiple +[QuickConfigure configure:] methods in order
        to define several closures to run after each example.
        Note that, since Quick makes no guarantee as to the order in which
        +[QuickConfiguration configure:] methods are evaluated, there is no
        guarantee as to the order in which afterEach closures are evaluated
        either. Multiple afterEach defined on a single configuration, however,
        will be executed in the order they're defined.
        - parameter closure: The closure to be executed before each example
                        in the test suite.
    */
    public func afterEach(_ closure: @escaping AfterExampleClosure) {
        exampleHooks.appendAfter(closure)
    }
    /**
        Like Quick.DSL.aroundEach, this configures Quick to wrap each example
        with the given closure. The closure passed to this method will wrap
        all examples globally across the test suite. You may call this method
        multiple times across multiple +[QuickConfigure configure:] methods in
        order to define several closures to wrap all examples.
        Note that, since Quick makes no guarantee as to the order in which
        +[QuickConfiguration configure:] methods are evaluated, there is no
        guarantee as to the order in which aroundEach closures are evaluated.
        However, aroundEach does always guarantee proper nesting of operations:
        cleanup within aroundEach closures will always happen in the reverse order
        of setup.
        - parameter closure: The closure to be executed before each example
                        in the test suite.
    */
    public func aroundEach(_ closure: @escaping AroundExampleClosure) {
        exampleHooks.appendAround(closure)
    }
    /**
        Identical to Quick.QCKConfiguration.aroundEach, except the closure receives
        metadata about the example that the closure wraps.
    */
    public func aroundEach(_ closure: @escaping AroundExampleWithMetadataClosure) {
        exampleHooks.appendAround(closure)
    }
    /**
        Like Quick.DSL.beforeSuite, this configures Quick to execute
        the given closure prior to any and all examples that are run.
        The two methods are functionally equivalent.
    */
    public func beforeSuite(_ closure: @escaping BeforeSuiteClosure) {
        suiteHooks.appendBefore(closure)
    }
    /**
        Like Quick.DSL.afterSuite, this configures Quick to execute
        the given closure after all examples have been run.
        The two methods are functionally equivalent.
    */
    public func afterSuite(_ closure: @escaping AfterSuiteClosure) {
        suiteHooks.appendAfter(closure)
    }
}
 | 
	bsd-3-clause | 
| 
	valine/octotap | 
	octo-tap/octo-tap/ViewControllers/SetupNavigationViewController.swift | 
	1 | 
	959 | 
	//  Copyright © 2017 Lukas Valine
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//  http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
import UIKit
class SetupNavigationViewController: UINavigationController {
    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.
    }
}
 | 
	apache-2.0 | 
| 
	KoCMoHaBTa/MHMessageKit | 
	MHMessageKit/Message/Implementation/NotificationCenter+MessageSubscriber.swift | 
	1 | 
	2630 | 
	//
//  NSNotificationCenter+MessageSubscriber.swift
//  MHMessageKit
//
//  Created by Milen Halachev on 1/15/16.
//  Copyright © 2016 Milen Halachev. All rights reserved.
//
import Foundation
extension NotificationCenter: MessageSubscriber {
    
    public func subscribe<M>(_ handler: @escaping (_ message: M) -> Void) -> MessageSubscription
    where M: Message {
        
        guard
        let messageType = M.self as? NotificationMessage.Type
        else {
            
            NSException(name: NSExceptionName.internalInconsistencyException, reason: "Only messages that also conform to NotificationMessage are supported", userInfo: nil).raise()
            return NotificationMessageSubscription(observer: "" as NSObjectProtocol)
        }
        
        let observer = self.addObserver(messageType: messageType, handler: { (message) -> Void in
            
            if let message = message as? M {
                
                handler(message)
                return
            }
            
            NSLog("Unhandled message \(messageType.notificationName()) - \(message)")
        })
        
        return NotificationMessageSubscription(observer: observer)
    }
    
    public func subscribe<M>(_ handler: @escaping (_ message: M) -> Void) -> WeakMessageSubscription
    where M: Message {
        
        guard
        let messageType = M.self as? NotificationMessage.Type
        else {
            
            NSException(name: NSExceptionName.internalInconsistencyException, reason: "Only messages that also conform to NotificationMessage are supported", userInfo: nil).raise()
            return NotificationWeakMessageSubscription(observer: "" as NSObjectProtocol)
        }
        
        let observer = self.addWeakObserver(messageType: messageType, handler: { (message) -> Void in
            
            if let message = message as? M {
                
                handler(message)
                return
            }
            
            NSLog("Unhandled message \(messageType.notificationName()) - \(message)")
        })
        
        return NotificationWeakMessageSubscription(observer: observer)
    }
    
    public func unsubscribe(from subscription: MessageSubscription) {
        
        guard let subscription = subscription as? NotificationMessageSubscription else {
            
            NSException(name: NSExceptionName.invalidArgumentException, reason: "Only subscriptions created by NotificationCenter are supported", userInfo: nil).raise()
            return
        }
        
        self.removeObserver(subscription.observer)
    }
}
 | 
	mit | 
| 
	Josscii/iOS-Demos | 
	UIButtonDemo/UIButtonDemo/ViewController.swift | 
	1 | 
	1528 | 
	//
//  ViewController.swift
//  UIButtonDemo
//
//  Created by josscii on 2017/9/27.
//  Copyright © 2017年 josscii. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let button = UIButton()
        button.backgroundColor = .green
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle("哈哈", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.setImage(#imageLiteral(resourceName: "love"), for: .normal)
        
        button.contentVerticalAlignment = .top
        button.contentHorizontalAlignment = .left
//        button.contentEdgeInsets.right = 30
//        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 30, bottom: 30, right: 0)
//        button.titleEdgeInsets = UIEdgeInsets(top: 30, left: 0, bottom: 0, right: 25)
        
        view.addSubview(button)
        
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.heightAnchor.constraint(equalToConstant: 100).isActive = true
        button.widthAnchor.constraint(equalToConstant: 100).isActive = true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
 | 
	mit | 
| 
	mownier/photostream | 
	Photostream/UI/Post Discovery/PostDiscoveryViewDelegate.swift | 
	1 | 
	4511 | 
	//
//  PostDiscoveryViewDelegate.swift
//  Photostream
//
//  Created by Mounir Ybanez on 20/12/2016.
//  Copyright © 2016 Mounir Ybanez. All rights reserved.
//
import UIKit
extension PostDiscoveryViewController {
    
    override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        
        presenter.initialPostWillShow()
        
        var condition: Bool = false
        
        switch sceneType {
        case .grid:
            condition = indexPath.row == presenter.postCount - 10
            
        case .list:
            condition = indexPath.section == presenter.postCount - 10
        }
        
        guard condition else {
            return
        }
        
        presenter.loadMorePosts()
    }
    
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch sceneType {
        case .grid:
            presenter.presentPostDiscoveryAsList(with: indexPath.row)
            
        default:
            break
        }
    }
}
extension PostDiscoveryViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        switch sceneType {
        case .grid:
            return gridLayout.itemSize
            
        case .list:
            let item = presenter.post(at: indexPath.section) as? PostListCollectionCellItem
            prototype.configure(with: item, isPrototype: true)
            let size = CGSize(width: listLayout.itemSize.width, height: prototype.dynamicHeight)
            return size
        }
    }
}
extension PostDiscoveryViewController: PostListCollectionCellDelegate {
    
    func didTapPhoto(cell: PostListCollectionCell) {
        guard let index = collectionView![cell]?.section else {
            return
        }
        
        presenter.likePost(at: index)
    }
    
    func didTapHeart(cell: PostListCollectionCell) {
        guard let index = collectionView![cell]?.section,
            let post = presenter.post(at: index) else {
                return
        }
        
        cell.toggleHeart(liked: post.isLiked) { [unowned self] in
            self.presenter.toggleLike(at: index)
        }
    }
    
    func didTapComment(cell: PostListCollectionCell) {
        guard let index = collectionView![cell]?.section else {
            return
        }
        
        presenter.presentCommentController(at: index, shouldComment: true)
    }
    
    func didTapCommentCount(cell: PostListCollectionCell) {
        guard let index = collectionView![cell]?.section else {
            return
        }
        
        presenter.presentCommentController(at: index)
    }
    
    func didTapLikeCount(cell: PostListCollectionCell) {
        guard let index = collectionView![cell]?.section else {
            return
        }
        
        presenter.presentPostLikes(at: index)
    }
}
extension PostDiscoveryViewController: PostListCollectionHeaderDelegate {
    
    func didTapDisplayName(header: PostListCollectionHeader, point: CGPoint) {
        willPresentUserTimeline(header: header, point: point)
    }
    
    func didTapAvatar(header: PostListCollectionHeader, point: CGPoint) {
        willPresentUserTimeline(header: header, point: point)
    }
    
    private func willPresentUserTimeline(header: PostListCollectionHeader, point: CGPoint) {
        var relativePoint = collectionView!.convert(point, from: header)
        relativePoint.y += header.frame.height
        guard let indexPath = collectionView!.indexPathForItem(at: relativePoint) else {
            return
        }
        
        presenter.presentUserTimeline(at: indexPath.section)
    }
}
extension PostDiscoveryViewController {
    
    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollHandler.isScrollable {
            if scrollHandler.isScrollingUp {
                scrollEventListener?.didScrollUp(
                    with: scrollHandler.offsetDelta,
                    offsetY: scrollHandler.currentOffsetY )
            } else if scrollHandler.isScrollingDown {
                scrollEventListener?.didScrollDown(
                    with: scrollHandler.offsetDelta,
                    offsetY: scrollHandler.currentOffsetY)
            }
            scrollHandler.update()
        }
    }
}
 | 
	mit | 
| 
	YevhenHerasymenko/SwiftGroup1 | 
	ConstraintsImage/ConstraintsImageUITests/ConstraintsImageUITests.swift | 
	1 | 
	1288 | 
	//
//  ConstraintsImageUITests.swift
//  ConstraintsImageUITests
//
//  Created by Yevhen Herasymenko on 24/06/2016.
//  Copyright © 2016 Yevhen Herasymenko. All rights reserved.
//
import XCTest
class ConstraintsImageUITests: XCTestCase {
        
    override func setUp() {
        super.setUp()
        
        // Put setup code here. This method is called before the invocation of each test method in the class.
        
        // In UI tests it is usually best to stop immediately when a failure occurs.
        continueAfterFailure = false
        // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
        XCUIApplication().launch()
        // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
    }
    
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    
    func testExample() {
        // Use recording to get started writing UI tests.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }
    
}
 | 
	apache-2.0 | 
| 
	GocePetrovski/ListCollectionViewKit | 
	ListCollectionViewKit/ListCollectionViewLayoutAttributes.swift | 
	1 | 
	1636 | 
	//
//  ListCollectionViewLayoutAttributes.swift
//  ListCollectionView
//
//  Created by Goce Petrovski on 27/01/2015.
//  Copyright (c) 2015 Pomarium. All rights reserved.
//  http://pomarium.com.au
import UIKit
open class ListCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes {
    open var editing:Bool = false
    open var shouldIndentWhileEditing:Bool = true
    open var editingStyle:ListCollectionViewCellEditingStyle = .delete
    
    // MARK: NSCopying
    
    override open func copy(with zone: NSZone? = nil) -> Any  {
        let attributes = super.copy(with: zone) as! ListCollectionViewLayoutAttributes
        
        attributes.editing = editing
        attributes.shouldIndentWhileEditing = shouldIndentWhileEditing
        attributes.editingStyle = editingStyle
        
        return attributes
    }
    
    
    // MARK: Equality
    
    override open func isEqual(_ object: Any?) -> Bool {
        if object == nil {
            return false
        }
        
        if let attributes = object as? ListCollectionViewLayoutAttributes {
            if super.isEqual(attributes) == false {
                return false
            }
            
            if editing != attributes.editing {
                return false
            }
            
            if shouldIndentWhileEditing != attributes.shouldIndentWhileEditing {
                return false
            }
            
            if editingStyle != attributes.editingStyle {
                return false
            }
            
            return true
        }
        
        return super.isEqual(object)
    }
    
}
 | 
	mit | 
| 
	sadawi/MagneticFields | 
	Pod/Classes/Observation.swift | 
	1 | 
	2068 | 
	//
//  Observation.swift
//  Pods
//
//  Created by Sam Williams on 11/28/15.
//
//
import Foundation
/**
 An object that holds a closure that is to be run when a value changes.
 
 `Observation` instances are themselves `Observable`, which means they can be chained:
 ```
 let a = Field<String>()
 let b = Field<String>()
 let c = Field<String>()
 a --> b --> c
 ```
 */
public class Observation<T>: Observable {
    public typealias ValueType = T
    
    public var observations = ObservationRegistry<T>()
    
    public var value:T? {
        get {
            return self.getValue?()
        }
        set {
            self.onChange?(newValue)
            self.notifyObservers()
        }
    }
    
    var onChange:(T? -> Void)?
    var getValue:(Void -> T?)?
    
    public func valueChanged(newValue:T?) {
        self.value = newValue
    }
}
/**
 A mapping of owner objects to Observations.  Owner references are weak.  Observation references are strong.
 */
public class ObservationRegistry<V> {
    var observations:NSMapTable = NSMapTable.weakToStrongObjectsMapTable()
    
    public init() { }
    func clear() {
        self.observations.removeAllObjects()
    }
    
    func each(closure:(Observation<V> -> Void)) {
        let enumerator = self.observations.objectEnumerator()
        
        while let observation = enumerator?.nextObject() {
            if let observation = observation as? Observation<V> {
                closure(observation)
            }
        }
    }
    
    func get<U:Observer where U.ValueType==V>(observer:U?) -> Observation<V>? {
        return self.observations.objectForKey(observer) as? Observation<V>
    }
    func setNil(observation:Observation<V>?) {
        self.observations.setObject(observation, forKey: DefaultObserverKey)
    }
    func set(owner:AnyObject, _ observation:Observation<V>?) {
        self.observations.setObject(observation, forKey: owner)
    }
    
    func remove<U:Observer where U.ValueType==V>(observer:U) {
        self.observations.removeObjectForKey(observer)
    }
}
 | 
	mit | 
| 
	seandavidmcgee/HumanKontactBeta | 
	src/keyboardTest/ActivityKeys.swift | 
	1 | 
	600 | 
	//
//  ActivityKeys.swift
//  keyboardTest
//
//  Created by Sean McGee on 7/22/15.
//  Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import Foundation
struct ActivityKeys {
    
    static let ChooseCall = "com.humankontact.keyboardtest.ChooseCall"
    static let ChooseText = "com.humankontact.keyboardtest.ChooseText"
    static let ChooseEmail = "com.humankontact.keyboardtest.ChooseEmail"
    static let ChoosePerson = "com.humankontact.keyboardtest.ChoosePerson"
    
    let ActivityItemsKey = "keyboardtest.items.key"
    let ActivityItemKey  = "keyboardtest.item.key"
}
 | 
	mit | 
| 
	bitjammer/swift | 
	test/decl/protocol/conforms/fixit_stub_editor.swift | 
	8 | 
	1027 | 
	// RUN: %target-typecheck-verify-swift -diagnostics-editor-mode
protocol P1 {
  func foo1()
  func foo2()
}
protocol P2 {
  func bar1()
  func bar2()
}
class C1 : P1, P2 {} // expected-error{{type 'C1' does not conform to protocol 'P1'}} expected-error{{type 'C1' does not conform to protocol 'P2'}} expected-note{{do you want to add protocol stubs?}}{{20-20=\n    func foo1() {\n        <#code#>\n    \}\n\n    func foo2() {\n        <#code#>\n    \}\n\n    func bar1() {\n        <#code#>\n    \}\n\n    func bar2() {\n        <#code#>\n    \}\n}}
protocol P3 {
  associatedtype T1
  associatedtype T2
  associatedtype T3
}
protocol P4 : P3 {
  associatedtype T4 = T1
  associatedtype T5 = T2
  associatedtype T6 = T3
}
class C2 : P4 {} // expected-error{{type 'C2' does not conform to protocol 'P4'}} expected-error{{type 'C2' does not conform to protocol 'P3'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n    typealias T1 = <#type#>\n\n    typealias T2 = <#type#>\n\n    typealias T3 = <#type#>\n}}
 | 
	apache-2.0 | 
| 
	Lickability/PinpointKit | 
	PinpointKit/PinpointKit/Sources/Core/UIGestureRecognizer+FailRecognizing.swift | 
	2 | 
	571 | 
	//
//  UIGestureRecognizer+FailRecognizing.swift
//  PinpointKit
//
//  Created by Kenneth Parker Ackerson on 1/24/16.
//  Copyright © 2016 Lickability. All rights reserved.
//
import UIKit
/// Extends `UIGestureRecognizer` to force a failure to recognize the gesture.
extension UIGestureRecognizer {
    
    /**
     Forces the receiver to fail.
     */
    func failRecognizing() {
        if !isEnabled {
            return
        }
        
        // Disabling and enabling causes recognizing to fail.
        isEnabled = false
        isEnabled = true
    }
}
 | 
	mit | 
| 
	prolificinteractive/Marker | 
	Marker/Marker/Parser/MarkdownParser.swift | 
	1 | 
	5152 | 
	//
//  MarkdownParser.swift
//  Marker
//
//  Created by Htin Linn on 5/4/16.
//  Copyright © 2016 Prolific Interactive. All rights reserved.
//
import Foundation
/// Markdown parser.
struct MarkdownParser {
    
    /// Parser error.
    ///
    /// - invalidTagSymbol: Tag symbol is not a Markdown symbol.
    enum ParserError: LocalizedError {
        case invalidTagSymbol
        var errorDescription: String? {
            return "Invalid Markdown tag."
        }
    }
    
    // MARK: - Private properties
    
    private static let underscoreEmSymbol = Symbol(character: "_")
    private static let asteriskEmSymbol = Symbol(character: "*")
    private static let underscoreStrongSymbol = Symbol(rawValue: "__")
    private static let asteriskStrongSymbol = Symbol(rawValue: "**")
    private static let tildeStrikethroughSymbol = Symbol(rawValue: "~~")
    private static let equalUnderlineSymbol = Symbol(rawValue: "==")
    private static let linkTextOpeningSymbol = Symbol(character: "[")
    private static let linkTextClosingSymbol = Symbol(character: "]")
    private static let linkURLOpeningSymbol = Symbol(character: "(")
    private static let linkURLClosingSymbol = Symbol(character: ")")
    
    // MARK: - Static functions
    
    /// Parses specified string and returns a tuple containing string stripped of symbols and an array of Markdown elements.
    ///
    /// - Parameter string: String to be parsed.
    /// - Returns: Tuple containing string stripped of tag characters and an array of Markdown elements.
    /// - Throws: Parser error.
    static func parse(_ string: String) throws -> (strippedString: String, elements: [MarkdownElement]) {
        guard
            let underscoreStrongSymbol = underscoreStrongSymbol,
            let asteriskStrongSymbol = asteriskStrongSymbol,
            let tildeStrikethroughSymbol = tildeStrikethroughSymbol,
            let equalUnderlineSymbol = equalUnderlineSymbol else {
                return (string, [])
        }
        let underscoreEmRule = Rule(symbol: underscoreEmSymbol)
        let asteriskEmRule = Rule(symbol: asteriskEmSymbol)
        let underscoreStrongRule = Rule(symbol: underscoreStrongSymbol)
        let asteriskStrongRule = Rule(symbol: asteriskStrongSymbol)
        let tildeStrikethroughRule = Rule(symbol: tildeStrikethroughSymbol)
        let equalUnderlineRule = Rule(symbol: equalUnderlineSymbol)
        let linkTextRule = Rule(openingSymbol: linkTextOpeningSymbol, closingSymbol: linkTextClosingSymbol)
        let linkURLRule = Rule(openingSymbol: linkURLOpeningSymbol, closingSymbol: linkURLClosingSymbol)
        let tokens = try TokenParser.parse(string,
                                           using: [underscoreEmRule,
                                                   asteriskEmRule,
                                                   underscoreStrongRule,
                                                   asteriskStrongRule,
                                                   tildeStrikethroughRule,
                                                   equalUnderlineRule,
                                                   linkTextRule,
                                                   linkURLRule])
        guard tokens.count > 0 else {
            return (string, [])
        }
        var strippedString = ""
        var elements: [MarkdownElement] = []
        var i = 0
        while i < tokens.count {
            let token = tokens[i]
            // For `em`, `strong`, and other single token rules,
            // it's just a matter of appending the content of matched token and storing the new range.
            // But, for links, look for the square brackets and make sure that it's followed by parentheses directly.
            // For everything else including parentheses by themseleves should be ignored.
            switch token.rule {
            case .some(underscoreEmRule), .some(asteriskEmRule):
                let range = strippedString.append(contentOf: token)
                elements.append(.em(range: range))
            case .some(underscoreStrongRule), .some(asteriskStrongRule):
                let range = strippedString.append(contentOf: token)
                elements.append(.strong(range: range))
            case .some(tildeStrikethroughRule):
                let range = strippedString.append(contentOf: token)
                elements.append(.strikethrough(range: range))
            case .some(equalUnderlineRule):
                let range = strippedString.append(contentOf: token)
                elements.append(.underline(range: range))
            case .some(linkTextRule):
                guard i + 1 < tokens.count, tokens[i + 1].rule == linkURLRule else {
                    fallthrough
                }
                let range = strippedString.append(contentOf: token)
                elements.append(.link(range: range,urlString: tokens[i + 1].string))
                i += 1
            default:
                strippedString += token.stringWithRuleSymbols
            }
            i += 1
        }
        return (strippedString, elements)
    }
    
}
 | 
	mit | 
| 
	gregomni/swift | 
	stdlib/public/Concurrency/AsyncSequence.swift | 
	3 | 
	19806 | 
	//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
/// A type that provides asynchronous, sequential, iterated access to its
/// elements.
///
/// An `AsyncSequence` resembles the `Sequence` type --- offering a list of
/// values you can step through one at a time --- and adds asynchronicity. An
/// `AsyncSequence` may have all, some, or none of its values available when
/// you first use it. Instead, you use `await` to receive values as they become
/// available.
///
/// As with `Sequence`, you typically iterate through an `AsyncSequence` with a
/// `for await`-`in` loop. However, because the caller must potentially wait for values,
/// you use the `await` keyword. The following example shows how to iterate
/// over `Counter`, a custom `AsyncSequence` that produces `Int` values from
/// `1` up to a `howHigh` value:
///
///     for await i in Counter(howHigh: 10) {
///         print(i, terminator: " ")
///     }
///     // Prints: 1 2 3 4 5 6 7 8 9 10
///
/// An `AsyncSequence` doesn't generate or contain the values; it just defines
/// how you access them. Along with defining the type of values as an associated
/// type called `Element`, the `AsyncSequence` defines a `makeAsyncIterator()`
/// method. This returns an instance of type `AsyncIterator`. Like the standard
/// `IteratorProtocol`, the `AsyncIteratorProtocol` defines a single `next()`
/// method to produce elements. The difference is that the `AsyncIterator`
/// defines its `next()` method as `async`, which requires a caller to wait for
/// the next value with the `await` keyword.
///
/// `AsyncSequence` also defines methods for processing the elements you
/// receive, modeled on the operations provided by the basic `Sequence` in the
/// standard library. There are two categories of methods: those that return a
/// single value, and those that return another `AsyncSequence`.
///
/// Single-value methods eliminate the need for a `for await`-`in` loop, and instead
/// let you make a single `await` call. For example, the `contains(_:)` method
/// returns a Boolean value that indicates if a given value exists in the
/// `AsyncSequence`. Given the `Counter` sequence from the previous example,
/// you can test for the existence of a sequence member with a one-line call:
///
///     let found = await Counter(howHigh: 10).contains(5) // true
///
/// Methods that return another `AsyncSequence` return a type specific to the
/// method's semantics. For example, the `.map(_:)` method returns a
/// `AsyncMapSequence` (or a `AsyncThrowingMapSequence`, if the closure you
/// provide to the `map(_:)` method can throw an error). These returned
/// sequences don't eagerly await the next member of the sequence, which allows
/// the caller to decide when to start work. Typically, you'll iterate over
/// these sequences with `for await`-`in`, like the base `AsyncSequence` you started
/// with. In the following example, the `map(_:)` method transforms each `Int`
/// received from a `Counter` sequence into a `String`:
///
///     let stream = Counter(howHigh: 10)
///         .map { $0 % 2 == 0 ? "Even" : "Odd" }
///     for await s in stream {
///         print(s, terminator: " ")
///     }
///     // Prints: Odd Even Odd Even Odd Even Odd Even Odd Even
///
@available(SwiftStdlib 5.1, *)
@rethrows
public protocol AsyncSequence {
  /// The type of asynchronous iterator that produces elements of this
  /// asynchronous sequence.
  associatedtype AsyncIterator: AsyncIteratorProtocol where AsyncIterator.Element == Element
  /// The type of element produced by this asynchronous sequence.
  associatedtype Element
  /// Creates the asynchronous iterator that produces elements of this
  /// asynchronous sequence.
  ///
  /// - Returns: An instance of the `AsyncIterator` type used to produce
  /// elements of the asynchronous sequence.
  __consuming func makeAsyncIterator() -> AsyncIterator
}
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
  /// Returns the result of combining the elements of the asynchronous sequence
  /// using the given closure.
  ///
  /// Use the `reduce(_:_:)` method to produce a single value from the elements of
  /// an entire sequence. For example, you can use this method on an sequence of
  /// numbers to find their sum or product.
  ///
  /// The `nextPartialResult` closure executes sequentially with an accumulating
  /// value initialized to `initialResult` and each element of the sequence.
  ///
  /// In this example, an asynchronous sequence called `Counter` produces `Int`
  /// values from `1` to `4`. The `reduce(_:_:)` method sums the values
  /// received from the asynchronous sequence.
  ///
  ///     let sum = await Counter(howHigh: 4)
  ///         .reduce(0) {
  ///             $0 + $1
  ///         }
  ///     print(sum)
  ///     // Prints: 10
  ///
  ///
  /// - Parameters:
  ///   - initialResult: The value to use as the initial accumulating value.
  ///     The `nextPartialResult` closure receives `initialResult` the first
  ///     time the closure runs.
  ///   - nextPartialResult: A closure that combines an accumulating value and
  ///     an element of the asynchronous sequence into a new accumulating value,
  ///     for use in the next call of the `nextPartialResult` closure or
  ///     returned to the caller.
  /// - Returns: The final accumulated value. If the sequence has no elements,
  ///   the result is `initialResult`.
  @inlinable
  public func reduce<Result>(
    _ initialResult: Result,
    _ nextPartialResult:
      (_ partialResult: Result, Element) async throws -> Result
  ) async rethrows -> Result {
    var accumulator = initialResult
    var iterator = makeAsyncIterator()
    while let element = try await iterator.next() {
      accumulator = try await nextPartialResult(accumulator, element)
    }
    return accumulator
  }
  /// Returns the result of combining the elements of the asynchronous sequence
  /// using the given closure, given a mutable initial value.
  ///
  /// Use the `reduce(into:_:)` method to produce a single value from the
  /// elements of an entire sequence. For example, you can use this method on a
  /// sequence of numbers to find their sum or product.
  ///
  /// The `nextPartialResult` closure executes sequentially with an accumulating
  /// value initialized to `initialResult` and each element of the sequence.
  ///
  /// Prefer this method over `reduce(_:_:)` for efficiency when the result is
  /// a copy-on-write type, for example an `Array` or `Dictionary`.
  ///
  /// - Parameters:
  ///   - initialResult: The value to use as the initial accumulating value.
  ///     The `nextPartialResult` closure receives `initialResult` the first
  ///     time the closure executes.
  ///   - nextPartialResult: A closure that combines an accumulating value and
  ///     an element of the asynchronous sequence into a new accumulating value,
  ///     for use in the next call of the `nextPartialResult` closure or
  ///     returned to the caller.
  /// - Returns: The final accumulated value. If the sequence has no elements,
  ///   the result is `initialResult`.
  @inlinable
  public func reduce<Result>(
    into initialResult: __owned Result,
    _ updateAccumulatingResult:
      (_ partialResult: inout Result, Element) async throws -> Void
  ) async rethrows -> Result {
    var accumulator = initialResult
    var iterator = makeAsyncIterator()
    while let element = try await iterator.next() {
      try await updateAccumulatingResult(&accumulator, element)
    }
    return accumulator
  }
}
@available(SwiftStdlib 5.1, *)
@inlinable
@inline(__always)
func _contains<Source: AsyncSequence>(
  _ self: Source,
  where predicate: (Source.Element) async throws -> Bool
) async rethrows -> Bool {
  for try await element in self {
    if try await predicate(element) {
      return true
    }
  }
  return false
}
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
  /// Returns a Boolean value that indicates whether the asynchronous sequence
  /// contains an element that satisfies the given predicate.
  ///
  /// You can use the predicate to check for an element of a type that doesn’t
  /// conform to the `Equatable` protocol, or to find an element that satisfies
  /// a general condition.
  ///
  /// In this example, an asynchronous sequence called `Counter` produces `Int`
  /// values from `1` to `10`. The `contains(where:)` method checks to see
  /// whether the sequence produces a value divisible by `3`:
  ///
  ///     let containsDivisibleByThree = await Counter(howHigh: 10)
  ///         .contains { $0 % 3 == 0 }
  ///     print(containsDivisibleByThree)
  ///     // Prints: true
  ///
  /// The predicate executes each time the asynchronous sequence produces an
  /// element, until either the predicate finds a match or the sequence ends.
  ///
  /// - Parameter predicate: A closure that takes an element of the asynchronous
  ///   sequence as its argument and returns a Boolean value that indicates
  ///   whether the passed element represents a match.
  /// - Returns: `true` if the sequence contains an element that satisfies
  ///   predicate; otherwise, `false`.
  @inlinable
  public func contains(
    where predicate: (Element) async throws -> Bool
  ) async rethrows -> Bool {
    return try await _contains(self, where: predicate)
  }
  
  /// Returns a Boolean value that indicates whether all elements produced by the
  /// asynchronous sequence satisfy the given predicate.
  ///
  /// In this example, an asynchronous sequence called `Counter` produces `Int`
  /// values from `1` to `10`. The `allSatisfy(_:)` method checks to see whether
  /// all elements produced by the sequence are less than `10`.
  ///
  ///     let allLessThanTen = await Counter(howHigh: 10)
  ///         .allSatisfy { $0 < 10 }
  ///     print(allLessThanTen)
  ///     // Prints: false
  ///
  /// The predicate executes each time the asynchronous sequence produces an
  /// element, until either the predicate returns `false` or the sequence ends.
  ///
  /// If the asynchronous sequence is empty, this method returns `true`.
  ///
  /// - Parameter predicate: A closure that takes an element of the asynchronous
  ///   sequence as its argument and returns a Boolean value that indicates
  ///   whether the passed element satisfies a condition.
  /// - Returns: `true` if the sequence contains only elements that satisfy
  ///   `predicate`; otherwise, `false`.
  @inlinable
  public func allSatisfy(
    _ predicate: (Element) async throws -> Bool
  ) async rethrows -> Bool {
    return try await !contains { try await !predicate($0) }
  }
}
@available(SwiftStdlib 5.1, *)
extension AsyncSequence where Element: Equatable {
  /// Returns a Boolean value that indicates whether the asynchronous sequence
  /// contains the given element.
  ///
  /// In this example, an asynchronous sequence called `Counter` produces `Int`
  /// values from `1` to `10`. The `contains(_:)` method checks to see whether
  /// the sequence produces the value `5`:
  ///
  ///     let containsFive = await Counter(howHigh: 10)
  ///         .contains(5)
  ///     print(containsFive)
  ///     // Prints: true
  ///
  /// - Parameter search: The element to find in the asynchronous sequence.
  /// - Returns: `true` if the method found the element in the asynchronous
  ///   sequence; otherwise, `false`.
  @inlinable
  public func contains(_ search: Element) async rethrows -> Bool {
    for try await element in self {
      if element == search {
        return true
      }
    }
    return false
  }
}
@available(SwiftStdlib 5.1, *)
@inlinable
@inline(__always)
func _first<Source: AsyncSequence>(
  _ self: Source,
  where predicate: (Source.Element) async throws -> Bool
) async rethrows -> Source.Element? {
  for try await element in self {
    if try await predicate(element) {
      return element
    }
  }
  return nil
}
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
  /// Returns the first element of the sequence that satisfies the given
  /// predicate.
  ///
  /// In this example, an asynchronous sequence called `Counter` produces `Int`
  /// values from `1` to `10`. The `first(where:)` method returns the first
  /// member of the sequence that's evenly divisible by both `2` and `3`.
  ///
  ///     let divisibleBy2And3 = await Counter(howHigh: 10)
  ///         .first { $0 % 2 == 0 && $0 % 3 == 0 }
  ///     print(divisibleBy2And3 ?? "none")
  ///     // Prints: 6
  ///
  /// The predicate executes each time the asynchronous sequence produces an
  /// element, until either the predicate finds a match or the sequence ends.
  ///
  /// - Parameter predicate: A closure that takes an element of the asynchronous
  ///  sequence as its argument and returns a Boolean value that indicates
  ///  whether the element is a match.
  /// - Returns: The first element of the sequence that satisfies `predicate`,
  ///   or `nil` if there is no element that satisfies `predicate`.
  @inlinable
  public func first(
    where predicate: (Element) async throws -> Bool
  ) async rethrows -> Element? {
    return try await _first(self, where: predicate)
  }
}
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
  /// Returns the minimum element in the asynchronous sequence, using the given
  /// predicate as the comparison between elements.
  ///
  /// Use this method when the asynchronous sequence's values don't conform
  /// to `Comparable`, or when you want to apply a custom ordering to the
  /// sequence.
  ///
  /// The predicate must be a *strict weak ordering* over the elements. That is,
  /// for any elements `a`, `b`, and `c`, the following conditions must hold:
  ///
  /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
  /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
  ///   both `true`, then `areInIncreasingOrder(a, c)` is also
  ///   `true`. (Transitive comparability)
  /// - Two elements are *incomparable* if neither is ordered before the other
  ///   according to the predicate. If `a` and `b` are incomparable, and `b`
  ///   and `c` are incomparable, then `a` and `c` are also incomparable.
  ///   (Transitive incomparability)
  ///
  /// The following example uses an enumeration of playing cards ranks, `Rank`,
  /// which ranges from `ace` (low) to `king` (high). An asynchronous sequence
  /// called `RankCounter` produces all elements of the array. The predicate
  /// provided to the `min(by:)` method sorts ranks based on their `rawValue`:
  ///
  ///     enum Rank: Int {
  ///         case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king
  ///     }
  ///
  ///     let min = await RankCounter()
  ///         .min { $0.rawValue < $1.rawValue }
  ///     print(min ?? "none")
  ///     // Prints: ace
  ///
  /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
  ///   first argument should be ordered before its second argument; otherwise,
  ///   `false`.
  /// - Returns: The sequence’s minimum element, according to
  ///   `areInIncreasingOrder`. If the sequence has no elements, returns `nil`.
  @inlinable
  @warn_unqualified_access
  public func min(
    by areInIncreasingOrder: (Element, Element) async throws -> Bool
  ) async rethrows -> Element? {
    var it = makeAsyncIterator()
    guard var result = try await it.next() else { 
      return nil 
    }
    while let e = try await it.next() {
      if try await areInIncreasingOrder(e, result) { 
        result = e 
      }
    }
    return result
  }
  
  /// Returns the maximum element in the asynchronous sequence, using the given
  /// predicate as the comparison between elements.
  ///
  /// Use this method when the asynchronous sequence's values don't conform
  /// to `Comparable`, or when you want to apply a custom ordering to the
  /// sequence.
  ///
  /// The predicate must be a *strict weak ordering* over the elements. That is,
  /// for any elements `a`, `b`, and `c`, the following conditions must hold:
  ///
  /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
  /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
  ///   both `true`, then `areInIncreasingOrder(a, c)` is also
  ///   `true`. (Transitive comparability)
  /// - Two elements are *incomparable* if neither is ordered before the other
  ///   according to the predicate. If `a` and `b` are incomparable, and `b`
  ///   and `c` are incomparable, then `a` and `c` are also incomparable.
  ///   (Transitive incomparability)
  ///
  /// The following example uses an enumeration of playing cards ranks, `Rank`,
  /// which ranges from `ace` (low) to `king` (high). An asynchronous sequence
  /// called `RankCounter` produces all elements of the array. The predicate
  /// provided to the `max(by:)` method sorts ranks based on their `rawValue`:
  ///
  ///     enum Rank: Int {
  ///         case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king
  ///     }
  ///
  ///     let max = await RankCounter()
  ///         .max { $0.rawValue < $1.rawValue }
  ///     print(max ?? "none")
  ///     // Prints: king
  ///
  /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
  ///   first argument should be ordered before its second argument; otherwise,
  ///   `false`.
  /// - Returns: The sequence’s minimum element, according to
  ///   `areInIncreasingOrder`. If the sequence has no elements, returns `nil`.
  @inlinable
  @warn_unqualified_access
  public func max(
    by areInIncreasingOrder: (Element, Element) async throws -> Bool
  ) async rethrows -> Element? {
    var it = makeAsyncIterator()
    guard var result = try await it.next() else { 
      return nil 
    }
    while let e = try await it.next() {
      if try await areInIncreasingOrder(result, e) { 
        result = e 
      }
    }
    return result
  }
}
@available(SwiftStdlib 5.1, *)
extension AsyncSequence where Element: Comparable {
  /// Returns the minimum element in an asynchronous sequence of comparable
  /// elements.
  ///
  /// In this example, an asynchronous sequence called `Counter` produces `Int`
  /// values from `1` to `10`. The `min()` method returns the minimum value
  /// of the sequence.
  ///
  ///     let min = await Counter(howHigh: 10)
  ///         .min()
  ///     print(min ?? "none")
  ///     // Prints: 1
  ///
  /// - Returns: The sequence’s minimum element. If the sequence has no
  ///   elements, returns `nil`.
  @inlinable
  @warn_unqualified_access
  public func min() async rethrows -> Element? {
    return try await self.min(by: <)
  }
  /// Returns the maximum element in an asynchronous sequence of comparable
  /// elements.
  ///
  /// In this example, an asynchronous sequence called `Counter` produces `Int`
  /// values from `1` to `10`. The `max()` method returns the max value
  /// of the sequence.
  ///
  ///     let max = await Counter(howHigh: 10)
  ///         .max()
  ///     print(max ?? "none")
  ///     // Prints: 10
  ///
  /// - Returns: The sequence’s maximum element. If the sequence has no
  ///   elements, returns `nil`.
  @inlinable
  @warn_unqualified_access
  public func max() async rethrows -> Element? {
    return try await self.max(by: <)
  }
}
 | 
	apache-2.0 | 
| 
	SimonFairbairn/Stormcloud | 
	Sources/Stormcloud/Error.swift | 
	1 | 
	2010 | 
	//
//  Error.swift
//  Stormcloud
//
//  Created by Simon Fairbairn on 25/10/2015.
//  Copyright © 2015 Voyage Travel Apps. All rights reserved.
//
import Foundation
/**
 Errors that Stormcloud can generate:
 
 - **InvalidJSON**:                     The JSON file to backup was invalid
 - **BackupFileExists**:                A backup file with the same name exists—usually this is caused by trying to write a new file faster than once a second
 - **CouldntSaveManagedObjectContext**: The passed `NSManagedObjectContext` was invalid
 - **CouldntSaveNewDocument**:          The document manager could not save the document
 - **CouldntMoveDocumentToiCloud**:     The backup document was created but could not be moved to iCloud
 - **CouldntDelete**:     The backup document was created but could not be moved to iCloud 
 - **iCloudUnavailable**:     The backup document was created but could not be moved to iCloud
 */
public enum StormcloudError : Int, Error {
    case invalidJSON = 100
    case couldntRestoreJSON
    case invalidURL
    case backupFileExists
    case couldntSaveManagedObjectContext
    case couldntSaveNewDocument
    case couldntMoveDocumentToiCloud
	case couldntMoveDocumentFromiCloud
    case couldntDelete
	case iCloudNotEnabled
    case iCloudUnavailable
    case backupInProgress
    case restoreInProgress
    case couldntOpenDocument
	case invalidDocumentData
	case entityDeleteFailed
	case otherError
    
    func domain() -> String {
        return "com.voyagetravelapps.Stormcloud"
    }
    
    func code() -> Int {
        return self.rawValue
    }
    func userInfo() -> [String : String]? {
        switch self {
        case .couldntMoveDocumentToiCloud:
            return [NSLocalizedDescriptionKey : "Couldn't get valid iCloud and local documents directories"]
        default:
            return nil
        }
    }
    
    func asNSError() -> NSError {
        return NSError(domain: self.domain(), code: self.code(), userInfo: self.userInfo())
    }
    
}
 | 
	mit | 
| 
	wireapp/wire-ios | 
	Wire-iOS/Sources/Developer/DeveloperTools/PreferredAPIVersion/PreferredAPIVersionViewModel.swift | 
	1 | 
	2764 | 
	//
// Wire
// Copyright (C) 2022 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireTransport
import WireSyncEngine
@available(iOS 14, *)
final class PreferredAPIVersionViewModel: ObservableObject {
    // MARK: - Models
    struct Section: Identifiable {
        let id = UUID()
        let header: String
        let items: [Item]
    }
    struct Item: Identifiable {
        let id = UUID()
        let title: String
        let value: Value
    }
    enum Value: Equatable {
        case noPreference
        case apiVersion(APIVersion)
        init(apiVersion: APIVersion?) {
            if let apiVersion = apiVersion {
                self = .apiVersion(apiVersion)
            } else {
                self = .noPreference
            }
        }
    }
    enum Event {
        case itemTapped(Item)
    }
    // MARK: - State
    let sections: [Section]
    @Published
    var selectedItemID: Item.ID
    // MARK: - Life cycle
    init() {
        sections = [
            Section(header: "", items: [Item(title: "No preference", value: .noPreference)]),
            Section(header: "Production versions", items: APIVersion.productionVersions.map {
                Item(title: String($0.rawValue), value: Value(apiVersion: $0))
            }),
            Section(header: "Development versions", items: APIVersion.developmentVersions.map {
                Item(title: String($0.rawValue), value: Value(apiVersion: $0))
            })
        ]
        // Initial selection
        let selectedItem = sections.flatMap(\.items).first { item in
            item.value == Value(apiVersion: BackendInfo.preferredAPIVersion)
        }!
        selectedItemID = selectedItem.id
    }
    // MARK: - Events
    func handleEvent(_ event: Event) {
        switch event {
        case let .itemTapped(item):
            selectedItemID = item.id
            switch item.value {
            case .noPreference:
                BackendInfo.preferredAPIVersion = nil
            case .apiVersion(let version):
                BackendInfo.preferredAPIVersion = version
            }
        }
    }
}
 | 
	gpl-3.0 | 
| 
	lbkchen/heis | 
	iOS/dimo/dimo/Array2D.swift | 
	1 | 
	641 | 
	//
//  Array2D.swift
//  dimo
//
//  Created by Ken Chen on 8/14/16.
//  Copyright © 2016 heis. All rights reserved.
//
import Foundation
class Array2D<T> {
    let columns: Int
    let rows: Int
    
    var array: Array<T?>
    
    init(columns: Int, rows: Int) {
        self.columns = columns
        self.rows = rows
        
        array = Array<T?>(count: rows * columns, repeatedValue: nil)
    }
    
    subscript(column: Int, row: Int) -> T? {
        get {
            return array[(row * columns) + column]
        }
        set(newValue) {
            array[(row * columns) + column] = newValue
        }
    }
    
    
} | 
	mit | 
| 
	saagarjha/Swimat | 
	Swimat/SwimatViewController.swift | 
	1 | 
	3767 | 
	import Cocoa
class SwimatViewController: NSViewController {
    let installPath = "/usr/local/bin/"
    @IBOutlet weak var swimatTabView: NSTabView!
    @IBOutlet weak var versionLabel: NSTextField! {
        didSet {
            guard let infoDictionary = Bundle.main.infoDictionary,
                let version = infoDictionary["CFBundleShortVersionString"],
                let build = infoDictionary[kCFBundleVersionKey as String] else {
                    return
            }
            versionLabel.stringValue = "Version \(version) (\(build))"
        }
    }
    @IBOutlet weak var installationLabel: NSTextField! {
        didSet {
            guard let url = Bundle.main.url(forResource: "Installation", withExtension: "html"),
                let string = try? NSAttributedString(url: url, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
                    return
            }
            installationLabel.attributedStringValue = string
        }
    }
    @IBOutlet weak var installButton: NSButton! {
        didSet {
            refreshInstallButton()
        }
    }
    @IBOutlet weak var parameterAlignmentCheckbox: NSButton! {
        didSet {
            parameterAlignmentCheckbox.state = Preferences.areParametersAligned ? .on : .off
        }
    }
    @IBOutlet weak var removeSemicolonsCheckbox: NSButton! {
        didSet {
            removeSemicolonsCheckbox.state = Preferences.areSemicolonsRemoved ? .on : .off
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
    }
    override func viewDidAppear() {
        guard let window = view.window else {
            return
        }
        window.titleVisibility = .hidden
        window.titlebarAppearsTransparent = true
    }
    @IBAction func install(_ sender: Any) {
        // Migrate this to SMJobBless?
        let path = Bundle.main.bundleURL
            .appendingPathComponent("Contents", isDirectory: true)
            .appendingPathComponent("Helpers", isDirectory: true)
            .appendingPathComponent("swimat")
            .path
        var error: NSDictionary?
        let script = NSAppleScript(source: "do shell script \"ln -s \'\(path)\' \(installPath)swimat\" with administrator privileges")
        script?.executeAndReturnError(&error)
        if error != nil {
            let alert = NSAlert()
            alert.messageText = "There was an error symlinking swimat."
            alert.informativeText = "You can try manually linking swimat by running:\n\nln -s /Applications/Swimat.app/Contents/Helpers/swimat \(installPath)swimat"
            alert.alertStyle = .warning
            alert.runModal()
        }
        refreshInstallButton()
    }
    @IBAction func updateParameterAlignment(_ sender: NSButton) {
        Preferences.areParametersAligned = sender.state == .on
        preferencesChanged()
    }
    @IBAction func updateRemoveSemicolons(_ sender: NSButton) {
        Preferences.areSemicolonsRemoved = sender.state == .on
        preferencesChanged()
    }
    func preferencesChanged() {
        let notification = Notification(name: Notification.Name("SwimatPreferencesChangedNotification"))
        NotificationCenter.default.post(notification)
    }
    func refreshInstallButton() {
        // Check for swimat, fileExists(atPath:) returns false for symlinks
        if (try? FileManager.default.attributesOfItem(atPath: "\(installPath)swimat")) != nil {
            installButton.title = "swimat installed to \(installPath)"
            installButton.isEnabled = false
        } else {
            installButton.title = "Install swimat to \(installPath)"
            installButton.isEnabled = true
        }
    }
}
 | 
	mit | 
| 
	SuperAwesomeLTD/sa-mobile-sdk-ios-demo | 
	AwesomeAdsDemo/SettingsDataSource.swift | 
	1 | 
	992 | 
	//
//  SettingsDataSource.swift
//  AwesomeAdsDemo
//
//  Created by Gabriel Coman on 10/10/2017.
//  Copyright © 2017 Gabriel Coman. All rights reserved.
//
import UIKit
class SettingsDataSource: NSObject, UITableViewDelegate, UITableViewDataSource {
    
    var data: [SettingViewModel] = []
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SettingRow.Identifier, for: indexPath) as! SettingRow
        cell.viewModel = data[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // do nothing
    }
}
 | 
	apache-2.0 | 
| 
	AndrewJByrne/GoodAsOldPhones-Swift | 
	GoodAsOldPhones/ContactViewController.swift | 
	1 | 
	535 | 
	//
//  ContactViewController.swift
//  GoodAsOldPhones
//
//  Created by Andrew Byrne on 3/4/16.
//  Copyright © 2016 Andrew Byrne. All rights reserved.
//
import UIKit
class ContactViewController: UIViewController {
    @IBOutlet weak var scrollView: UIScrollView!
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(scrollView)
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        scrollView.contentSize = CGSizeMake(375, 800)
    }
}
 | 
	mit | 
| 
	sunshineclt/NKU-Helper | 
	NKU Helper/今天/TodayCell/GeneralTaskCell.swift | 
	1 | 
	1167 | 
	//
//  GeneralTaskCell.swift
//  NKU Helper
//
//  Created by 陈乐天 on 16/7/28.
//  Copyright © 2016年 陈乐天. All rights reserved.
//
import UIKit
class GeneralTaskCell: MCSwipeTableViewCell {
    @IBOutlet var containerView: UIView!
    @IBOutlet var colorView: UIView!
    @IBOutlet var titleLabel: UILabel!
    @IBOutlet var descriptionLabel: UILabel!
    @IBOutlet var timeLabel: UILabel!
    
    var task: Task! {
        didSet {
            colorView.backgroundColor = task.color?.convertToUIColor() ?? UIColor.gray
            titleLabel.text = task.title
            descriptionLabel.text = task.descrip
            guard let dueDate = task.dueDate else {
                timeLabel.text = ""
                return
            }
            timeLabel.text = CalendarHelper.getCustomTimeIntervalDisplay(toDate: dueDate)
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        containerView.layer.shadowOffset = CGSize(width: 2, height: 2)
        containerView.layer.shadowColor = UIColor.gray.cgColor
        containerView.layer.shadowRadius = 2
        containerView.layer.shadowOpacity = 0.5
    }
    
}
 | 
	gpl-3.0 | 
| 
	almazrafi/Metatron | 
	Sources/MPEG/MPEGMedia.swift | 
	1 | 
	15527 | 
	//
//  MPEGMedia.swift
//  Metatron
//
//  Copyright (c) 2016 Almaz Ibragimov
//
//  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
public class MPEGMedia {
    // MARK: Instance Properties
    private let stream: Stream
    private var introID3v2TagSlot: MPEGMediaIntroSlot<ID3v2TagCreator>
    private var outroID3v2TagSlot: MPEGMediaOutroSlot<ID3v2TagCreator>
    private var outroAPETagSlot: MPEGMediaOutroSlot<APETagCreator>
    private var outroLyrics3TagSlot: MPEGMediaOutroSlot<Lyrics3TagCreator>
    private var outroID3v1TagSlot: MPEGMediaOutroSlot<ID3v1TagCreator>
    private let properties: MPEGProperties
    // MARK:
    public var introID3v2Tag: ID3v2Tag? {
        get {
            return self.introID3v2TagSlot.tag
        }
        set {
            self.introID3v2TagSlot.tag = newValue
        }
    }
    public var outroID3v2Tag: ID3v2Tag? {
        get {
            return self.outroID3v2TagSlot.tag
        }
        set {
            self.outroID3v2TagSlot.tag = newValue
        }
    }
    public var outroAPETag: APETag? {
        get {
            return self.outroAPETagSlot.tag
        }
        set {
            self.outroAPETagSlot.tag = newValue
        }
    }
    public var outroLyrics3Tag: Lyrics3Tag? {
        get {
            return self.outroLyrics3TagSlot.tag
        }
        set {
            self.outroLyrics3TagSlot.tag = newValue
        }
    }
    public var outroID3v1Tag: ID3v1Tag? {
        get {
            return self.outroID3v1TagSlot.tag
        }
        set {
            self.outroID3v1TagSlot.tag = newValue
        }
    }
    // MARK:
    public var version: MPEGVersion {
        return self.properties.version
    }
    public var layer: MPEGLayer {
        return self.properties.layer
    }
    public var duration: Double {
        return self.properties.duration
    }
    public var bitRate: Int {
        return self.properties.bitRate
    }
    public var sampleRate: Int {
        return self.properties.sampleRate
    }
    public var channelMode: MPEGChannelMode {
        return self.properties.channelMode
    }
    public var copyrighted: Bool {
        return self.properties.copyrighted
    }
    public var original: Bool {
        return self.properties.original
    }
    public var emphasis: MPEGEmphasis {
        return self.properties.emphasis
    }
    public var bitRateMode: MPEGBitRateMode {
        return self.properties.bitRateMode
    }
    public var xingHeader: MPEGXingHeader? {
        return self.properties.xingHeader
    }
    public var vbriHeader: MPEGVBRIHeader? {
        return self.properties.vbriHeader
    }
    public var channels: Int {
        switch self.channelMode {
        case MPEGChannelMode.stereo, MPEGChannelMode.jointStereo, MPEGChannelMode.dualChannel:
            return 2
        case MPEGChannelMode.singleChannel:
            return 1
        }
    }
    // MARK:
    public var filePath: String {
        if let stream = self.stream as? FileStream {
            return stream.filePath
        }
        return ""
    }
    public var isReadOnly: Bool {
        return (!self.stream.isWritable)
    }
    // MARK: Initializers
    public init(fromStream stream: Stream) throws {
        guard stream.isOpen && stream.isReadable && (stream.length > 0) else {
            throw MediaError.invalidStream
        }
        var range = Range<UInt64>(0..<stream.length)
        var introID3v2TagSlot: MPEGMediaIntroSlot<ID3v2TagCreator>?
        var outroID3v2TagSlot: MPEGMediaOutroSlot<ID3v2TagCreator>?
        var outroAPETagSlot: MPEGMediaOutroSlot<APETagCreator>?
        var outroLyrics3TagSlot: MPEGMediaOutroSlot<Lyrics3TagCreator>?
        var outroID3v1TagSlot: MPEGMediaOutroSlot<ID3v1TagCreator>?
        if let slot = MPEGMediaIntroSlot(creator: ID3v2TagCreator.regular, stream: stream, range: range) {
            range = slot.range.upperBound..<range.upperBound
            while let excess = MPEGMediaIntroSlot(creator: ID3v2TagCreator.regular, stream: stream, range: range) {
                range = excess.range.upperBound..<range.upperBound
            }
            slot.range = slot.range.lowerBound..<range.lowerBound
            if slot.tag!.fillingLength > 0 {
                slot.tag!.fillingLength = Int(min(UInt64(slot.range.count), UInt64(Int.max)))
            }
            introID3v2TagSlot = slot
        }
        if let slot = MPEGMediaOutroSlot(creator: APETagCreator.regular, stream: stream, range: range) {
            range = range.lowerBound..<slot.range.lowerBound
            outroAPETagSlot = slot
        }
        if let slot = MPEGMediaOutroSlot(creator: Lyrics3TagCreator.regular, stream: stream, range: range) {
            range = range.lowerBound..<slot.range.lowerBound
            outroLyrics3TagSlot = slot
            if outroAPETagSlot == nil {
                if let slot = MPEGMediaOutroSlot(creator: APETagCreator.regular, stream: stream, range: range) {
                    range = range.lowerBound..<slot.range.lowerBound
                    outroAPETagSlot = slot
                }
            }
        }
        if let slot = MPEGMediaOutroSlot(creator: ID3v1TagCreator.regular, stream: stream, range: range) {
            range = range.lowerBound..<slot.range.lowerBound
            outroID3v1TagSlot = slot
            if let slot = MPEGMediaOutroSlot(creator: APETagCreator.regular, stream: stream, range: range) {
                range = range.lowerBound..<slot.range.lowerBound
                outroAPETagSlot = slot
            }
            if let slot = MPEGMediaOutroSlot(creator: Lyrics3TagCreator.regular, stream: stream, range: range) {
                range = range.lowerBound..<slot.range.lowerBound
                outroLyrics3TagSlot = slot
                if outroAPETagSlot == nil {
                    if let slot = MPEGMediaOutroSlot(creator: APETagCreator.regular, stream: stream, range: range) {
                        range = range.lowerBound..<slot.range.lowerBound
                        outroAPETagSlot = slot
                    }
                }
            }
        }
        if let slot = MPEGMediaOutroSlot(creator: ID3v2TagCreator.regular, stream: stream, range: range) {
            range = range.lowerBound..<slot.range.lowerBound
            outroID3v2TagSlot = slot
        }
        guard let properties = MPEGProperties(fromStream: stream, range: range) else {
            throw MediaError.invalidFormat
        }
        self.stream = stream
        self.introID3v2TagSlot = introID3v2TagSlot ?? MPEGMediaIntroSlot()
        self.outroID3v2TagSlot = outroID3v2TagSlot ?? MPEGMediaOutroSlot()
        self.outroAPETagSlot = outroAPETagSlot ?? MPEGMediaOutroSlot()
        self.outroLyrics3TagSlot = outroLyrics3TagSlot ?? MPEGMediaOutroSlot()
        self.outroID3v1TagSlot = outroID3v1TagSlot ?? MPEGMediaOutroSlot()
        self.properties = properties
    }
    public convenience init(fromFilePath filePath: String, readOnly: Bool) throws {
        guard !filePath.isEmpty else {
            throw MediaError.invalidFile
        }
        let stream = FileStream(filePath: filePath)
        if readOnly {
            guard stream.openForReading() else {
                throw MediaError.invalidFile
            }
        } else {
            guard stream.openForUpdating(truncate: false) else {
                throw MediaError.invalidFile
            }
        }
        guard stream.length > 0 else {
            throw MediaError.invalidData
        }
        try self.init(fromStream: stream)
    }
    public convenience init(fromData data: [UInt8], readOnly: Bool) throws {
        guard !data.isEmpty else {
            throw MediaError.invalidData
        }
        let stream = MemoryStream(data: data)
        if readOnly {
            guard stream.openForReading() else {
                throw MediaError.invalidStream
            }
        } else {
            guard stream.openForUpdating(truncate: false) else {
                throw MediaError.invalidStream
            }
        }
        try self.init(fromStream: stream)
    }
    // MARK: Instance Methods
    @discardableResult
    public func save() -> Bool {
        guard self.stream.isOpen && self.stream.isWritable && (self.stream.length > 0) else {
            return false
        }
        guard self.stream.seek(offset: self.introID3v2TagSlot.range.lowerBound) else {
            return false
        }
        if let data = self.introID3v2TagSlot.tag?.toData() {
            let range = self.introID3v2TagSlot.range
            if range.upperBound == 0 {
                guard self.stream.insert(data: data) else {
                    return false
                }
                self.introID3v2TagSlot.range = range.lowerBound..<self.stream.offset
                let framesLowerBound = self.properties.framesRange.lowerBound + UInt64(data.count)
                let framesUpperBound = self.properties.framesRange.upperBound + UInt64(data.count)
                self.properties.framesRange = framesLowerBound..<framesUpperBound
            } else if UInt64(data.count) > UInt64(range.count) {
                let delta = UInt64(data.count) - UInt64(range.count)
                guard self.stream.write(data: [UInt8](data.prefix(Int(range.count)))) == Int(range.count) else {
                    return false
                }
                guard self.stream.insert(data: [UInt8](data.suffix(Int(delta)))) else {
                    return false
                }
                self.introID3v2TagSlot.range = range.lowerBound..<self.stream.offset
                let framesLowerBound = self.properties.framesRange.lowerBound + delta
                let framesUpperBound = self.properties.framesRange.upperBound + delta
                self.properties.framesRange = framesLowerBound..<framesUpperBound
            } else {
                guard self.stream.write(data: data) == data.count else {
                    return false
                }
                if range.upperBound > self.stream.offset {
                    let delta = range.upperBound - self.stream.offset
                    guard self.stream.remove(length: delta) else {
                        return false
                    }
                    self.introID3v2TagSlot.range = range.lowerBound..<self.stream.offset
                    let framesLowerBound = self.properties.framesRange.lowerBound - delta
                    let framesUpperBound = self.properties.framesRange.upperBound - delta
                    self.properties.framesRange = framesLowerBound..<framesUpperBound
                }
            }
            self.introID3v2TagSlot.range = range
        } else {
            let rangeLength = UInt64(self.introID3v2TagSlot.range.count)
            guard self.stream.remove(length: rangeLength) else {
                return false
            }
            self.introID3v2TagSlot.range = 0..<0
            let framesLowerBound = self.properties.framesRange.lowerBound - rangeLength
            let framesUpperBound = self.properties.framesRange.upperBound - rangeLength
            self.properties.framesRange = framesLowerBound..<framesUpperBound
        }
        guard self.stream.seek(offset: self.properties.framesRange.upperBound) else {
            return false
        }
        var nextLowerBound = self.stream.offset
        if let tag = self.outroID3v2TagSlot.tag {
            tag.version = ID3v2Version.v4
            tag.footerPresent = true
            tag.fillingLength = 0
            if let data = tag.toData() {
                guard self.stream.write(data: data) == data.count else {
                    return false
                }
                self.outroID3v2TagSlot.range = nextLowerBound..<self.stream.offset
            } else {
                self.outroID3v2TagSlot.range = 0..<0
            }
        } else {
            self.outroID3v2TagSlot.range = 0..<0
        }
        nextLowerBound = self.stream.offset
        if let tag = self.outroAPETagSlot.tag {
            tag.version = APEVersion.v2
            tag.footerPresent = true
            tag.fillingLength = 0
            if let data = tag.toData() {
                guard self.stream.write(data: data) == data.count else {
                    return false
                }
                self.outroAPETagSlot.range = nextLowerBound..<self.stream.offset
            } else {
                self.outroAPETagSlot.range = 0..<0
            }
        } else {
            self.outroAPETagSlot.range = 0..<0
        }
        nextLowerBound = self.stream.offset
        if let data = self.outroLyrics3TagSlot.tag?.toData() {
            guard self.stream.write(data: data) == data.count else {
                return false
            }
            self.outroLyrics3TagSlot.range = nextLowerBound..<self.stream.offset
        } else {
            self.outroLyrics3TagSlot.range = 0..<0
        }
        nextLowerBound = self.stream.offset
        if let tag = self.outroID3v1TagSlot.tag {
            let extVersionAvailable: Bool
            if self.outroID3v2TagSlot.range.lowerBound > 0 {
                extVersionAvailable = false
            } else if self.outroAPETagSlot.range.lowerBound > 0 {
                extVersionAvailable = false
            } else if self.outroLyrics3TagSlot.range.lowerBound > 0 {
                extVersionAvailable = false
            } else {
                extVersionAvailable = true
            }
            if !extVersionAvailable {
                switch tag.version {
                case ID3v1Version.vExt0:
                    tag.version = ID3v1Version.v0
                case ID3v1Version.vExt1:
                    tag.version = ID3v1Version.v1
                case ID3v1Version.v0, ID3v1Version.v1:
                    break
                }
            }
            if let data = tag.toData() {
                guard self.stream.write(data: data) == data.count else {
                    return false
                }
                self.outroID3v1TagSlot.range = nextLowerBound..<self.stream.offset
            } else {
                self.outroID3v1TagSlot.range = 0..<0
            }
        } else {
            self.outroID3v1TagSlot.range = 0..<0
        }
        self.stream.truncate(length: self.stream.offset)
        self.stream.synchronize()
        return true
    }
}
 | 
	mit | 
| 
	natecook1000/swift-compiler-crashes | 
	fixed/00922-swift-lexer-getlocforendoftoken.swift | 
	11 | 
	235 | 
	// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
func b(){
{
protocol b{init<>(
}
}
}
}
func a<T{
struct c{
}
c() | 
	mit | 
| 
	natecook1000/swift-compiler-crashes | 
	fixed/26999-swift-genericsignature-profile.swift | 
	4 | 
	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
let c{{enum S{struct A<h{struct S{func A{let c<{a d{b:{a{a{let:{{}struct A{let:{class A{func a{b=1
 | 
	mit | 
| 
	18775134221/SwiftBase | 
	SwiftTest/SwiftTest/Classes/Main/Tools/SQLite/SQLiteDatabaseTool.swift | 
	2 | 
	6708 | 
	//
//  SQLiteDatabaseTool.swift
//  SwiftTest
//
//  Created by MAC on 2016/12/31.
//  Copyright © 2016年 MAC. All rights reserved.
//
import UIKit
class SQLiteDatabaseTool: NSObject {
    
    // 创建单例
    static var sharedInstance : SQLiteDatabaseTool {
        struct Static {
            static let instance : SQLiteDatabaseTool = SQLiteDatabaseTool()
        }
        return Static.instance
    }
    
    // 数据库对象
    private var db:OpaquePointer? = nil
    
    // 创建一个串行队列
    private let dbQueue = DispatchQueue(label: "task", attributes: .init(rawValue: 0))
    
    func execQueueSQL(action: @escaping (_ manager: SQLiteDatabaseTool)->())
    {
        // 1.开启一个子线程
        dbQueue.async(execute: {
            action(self)
        })
    }
    
    /**
     打开数据库
     :param: SQLiteName 数据库名称
     */
    func openDB(SQLiteName: String)
    {
        // 0.拿到数据库的路径
        let path = SQLiteName.docDir()
        let cPath = path.cString(using: String.Encoding.utf8)!
        // 1.打开数据库
        /*
         1.需要打开的数据库文件的路径, C语言字符串
         2.打开之后的数据库对象 (指针), 以后所有的数据库操作, 都必须要拿到这个指针才能进行相关操作
         */
        // open方法特点: 如果指定路径对应的数据库文件已经存在, 就会直接打开
        //              如果指定路径对应的数据库文件不存在, 就会创建一个新的
        if sqlite3_open(cPath, &db) != SQLITE_OK
        {
            print("打开数据库失败")
            return
        }
        
        // 2.创建表
        if creatTable()
        {
            print("创建表成功")
        }else
        {
            print("创建表失败")
        }
    }
    
    private func creatTable() -> Bool
    {
        // 1.编写SQL语句
        // 建议: 在开发中编写SQL语句, 如果语句过长, 不要写在一行
        // 开发技巧: 在做数据库开发时, 如果遇到错误, 可以先将SQL打印出来, 拷贝到PC工具中验证之后再进行调试
        let sql = "CREATE TABLE IF NOT EXISTS T_Person( \n" +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, \n" +
            "name TEXT, \n" +
            "age INTEGER \n" +
        "); \n"
        //        print(sql)
        // 2.执行SQL语句
        return execSQL(sql: sql)
    }
    
    /**
     执行除查询以外的SQL语句
     
     :param: sql 需要执行的SQL语句
     
     :returns: 是否执行成功 true执行成功 false执行失败
     */
    func execSQL(sql: String) -> Bool
    {
        // 0.将Swift字符串转换为C语言字符串
        let cSQL = sql.cString(using: String.Encoding.utf8)!
        
        // 在SQLite3中, 除了查询意外(创建/删除/新增/更新)都使用同一个函数
        /*
         1. 已经打开的数据库对象
         2. 需要执行的SQL语句, C语言字符串
         3. 执行SQL语句之后的回调, 一般传nil
         4. 是第三个参数的第一个参数, 一般传nil
         5. 错误信息, 一般传nil
         */
        if sqlite3_exec(db, cSQL, nil, nil, nil) != SQLITE_OK
        {
            return false
        }
        return true
    }
    
    /**
     查询所有的数据
     :returns: 查询到的字典数组
     */
    func execRecordSQL(sql: String) ->[[String: AnyObject]]
    {
        // 0.将Swift字符串转换为C语言字符串
        let cSQL = sql.cString(using: String.Encoding.utf8)!
        
        // 1.准备数据
        // 准备: 理解为预编译SQL语句, 检测里面是否有错误等等, 它可以提供性能
        /*
         1.已经开打的数据库对象
         2.需要执行的SQL语句
         3.需要执行的SQL语句的长度, 传入-1系统自动计算
         4.预编译之后的句柄, 已经要想取出数据, 就需要这个句柄
         5. 一般传nil
         */
        var stmt: OpaquePointer? = nil
        if sqlite3_prepare_v2(db, cSQL, -1, &stmt, nil) != SQLITE_OK
        {
            print("准备失败")
        }
        
        // 准备成功
        var records = [[String: AnyObject]]()
        
        // 2.查询数据
        // sqlite3_step代表取出一条数据, 如果取到了数据就会返回SQLITE_ROW
        while sqlite3_step(stmt) == SQLITE_ROW
        {
            // 获取一条记录的数据
            let record = recordWithStmt(stmt: stmt!)
            // 将当前获取到的这一条记录添加到数组中
            records.append(record)
        }
        
        // 返回查询到的数据
        return records
    }
    
    /**
     获取一条记录的值
     
     :param: stmt 预编译好的SQL语句
     
     :returns: 字典
     */
    private func recordWithStmt(stmt: OpaquePointer) ->[String: AnyObject]
    {
        // 2.1拿到当前这条数据所有的列
        let count = sqlite3_column_count(stmt)
        //            print(count)
        // 定义字典存储查询到的数据
        var record  = [String: AnyObject]()
        
        for index in 0..<count
        {
            // 2.2拿到每一列的名称
            let cName = sqlite3_column_name(stmt, index)
            let name = String(cString: cName!, encoding: String.Encoding.utf8)
            //                print(name)
            // 2.3拿到每一列的类型 SQLITE_INTEGER
            let type = sqlite3_column_type(stmt, index)
            //                print("name = \(name) , type = \(type)")
            
            switch type
            {
            case SQLITE_INTEGER:
                // 整形
                let num = sqlite3_column_int64(stmt, index)
                record[name!] = Int(num) as AnyObject?
            case SQLITE_FLOAT:
                // 浮点型
                let double = sqlite3_column_double(stmt, index)
                record[name!] = Double(double) as AnyObject?
            case SQLITE3_TEXT:
                // 文本类型
                //let cText =
                let text = String(cString: sqlite3_column_text(stmt, index))
                //(sqlite3_column_text(stmt, index))
//                let text = String(cString: cText! , encoding: String.Encoding.utf8)
                record[name!] = text as AnyObject?
            case SQLITE_NULL:
                // 空类型
                record[name!] = NSNull()
            default:
                // 二进制类型 SQLITE_BLOB
                // 一般情况下, 不会往数据库中存储二进制数据
                print("")
            }
        }
        return record
    }
}
 | 
	apache-2.0 | 
| 
	airspeedswift/swift-compiler-crashes | 
	crashes-fuzzing/01941-swift-optionaltype-get.swift | 
	1 | 
	225 | 
	// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
0
(x: BooleanType)? ->
class A {
class A {
func a<I : a
 | 
	mit | 
| 
	airspeedswift/swift-compiler-crashes | 
	crashes-fuzzing/00896-void.swift | 
	1 | 
	212 | 
	// 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 {
deinit {
class B : A
class A : A
 | 
	mit | 
| 
	buyiyang/iosstar | 
	iOSStar/Scenes/Discover/Controllers/VoiceAskVC.swift | 
	3 | 
	4229 | 
	//
//  VoiceAskVC.swift
//  iOSStar
//
//  Created by mu on 2017/8/17.
//  Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import SVProgressHUD
class VoiceAskVC: BaseTableViewController ,UITextViewDelegate{
    
   
    @IBOutlet var contentText: UITextView!
 
    @IBOutlet var placeholdLabel: UILabel!
    @IBOutlet weak var countLabel: UILabel!
    @IBOutlet weak var voice15Btn: UIButton!
    @IBOutlet weak var voice30Btn: UIButton!
    @IBOutlet weak var voice60Btn: UIButton!
    @IBOutlet var switchopen: UISwitch!
    var starModel: StarSortListModel = StarSortListModel()
    private var lastVoiceBtn: UIButton?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "向TA定制"
        voiceBtnTapped(voice15Btn)
        navright()
    }
    
    @IBAction func voiceBtnTapped(_ sender: UIButton) {
        lastVoiceBtn?.isSelected = false
        sender.isSelected = !sender.isSelected
        lastVoiceBtn = sender
    }
    func navright(){
        let share = UIButton.init(type: .custom)
        share.frame = CGRect.init(x: 0, y: 0, width: 70, height: 30)
        share.setTitle("发布", for: .normal)
        share.titleLabel?.font = UIFont.systemFont(ofSize: 17)
        share.setTitleColor(UIColor.init(hexString: AppConst.Color.main), for: .normal)
        share.addTarget(self, action: #selector(publish), for: .touchUpInside)
        let item = UIBarButtonItem.init(customView: share)
        self.navigationItem.rightBarButtonItem = item
        NotificationCenter.default.addObserver(self, selector: #selector(textViewNotifitionAction), name: NSNotification.Name.UITextViewTextDidChange, object: nil);
        NotificationCenter.default.addObserver(self, selector: #selector(textViewNotifitionAction), name: NSNotification.Name.UITextViewTextDidChange, object: nil);
    }
    func publish(){
        if contentText.text == ""{
            SVProgressHUD.showErrorMessage(ErrorMessage: "请输入问答内容", ForDuration: 2, completion: nil)
            return
        }
        let request = AskRequestModel()
        request.pType = switchopen.isOn ? 1 : 0
        request.aType = 2
        request.starcode = starModel.symbol
        request.uask = contentText.text!
        request.videoUrl = ""
        request.cType = voice15Btn.isSelected ? 0 : (voice30Btn.isSelected ? 1 : (voice60Btn.isSelected ? 3 : 1))
        AppAPIHelper.discoverAPI().videoAskQuestion(requestModel:request, complete: { (result) in
            if let model = result as? ResultModel{
                if model.result == 0{
                    SVProgressHUD.showSuccessMessage(SuccessMessage: "语音问答成功", ForDuration: 1, completion: {
                        self.navigationController?.popViewController(animated: true)
                    })
                }
                if model.result == 1{
                    SVProgressHUD.showErrorMessage(ErrorMessage: "时间不足", ForDuration: 2, completion: nil)
                }
            }
        }) { (error) in
            self.didRequestError(error)
        }
        
        
    }
    // 限制不超过200字
    
    func textViewNotifitionAction(userInfo:NSNotification){
        let textVStr = contentText.text as! NSString
        
        if ((textVStr.length) > 100) {
            contentText.text = contentText.text.substring(to: contentText.text.index(contentText.text.startIndex, offsetBy: 100))
            contentText.resignFirstResponder()
            return
        }else{
            countLabel.text = "\(textVStr.length)/100"
        }
        
    }
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if (contentText.text.length() > 100){
          return false
        }
         return true
    }
    func textViewDidChange(_ textView: UITextView) {
//        contentText.text = textView.text
        if textView.text == "" {
            placeholdLabel.text = "输入你的问题,可选择公开或者私密,公开提问能被其他用户所见 "
            placeholdLabel.isHidden = false
        } else {
            placeholdLabel.text = ""
            placeholdLabel.isHidden = true
        }
    }
}
 | 
	gpl-3.0 | 
| 
	qmathe/Confetti | 
	Event/Input/Modifiers.swift | 
	1 | 
	533 | 
	/**
	Copyright (C) 2017 Quentin Mathe
	Author:  Quentin Mathe <[email protected]>
	Date:  November 2017
	License:  MIT
 */
import Foundation
import Tapestry
public struct Modifiers: OptionSet {
    public let rawValue: Int
    
    public init(rawValue: Int) {
        self.rawValue = rawValue
    }
    
    public static let command = Modifiers(rawValue: 1)
    public static let option = Modifiers(rawValue: 2)
    public static let control = Modifiers(rawValue: 4)
    public static let shift = Modifiers(rawValue: 8)
}
 | 
	mit | 
| 
	rxwei/dlvm-tensor | 
	Sources/CoreTensor/Index.swift | 
	2 | 
	5000 | 
	//
//  Index.swift
//  CoreTensor
//
//  Copyright 2016-2018 The DLVM Team.
//
//  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.
//
/// Tensor index
public struct TensorIndex: ExpressibleByArrayLiteral {
    var elements: [Int]
    public init(arrayLiteral elements: Int...) {
        self.elements = elements
    }
    public init(_ indexElements: Int...) {
        self.elements = indexElements
    }
    public init<S: Sequence>(_ indexElements: S) where S.Element == Int {
        self.elements = Array(indexElements)
    }
    public init(repeating repeatedValue: Int, count: Int) {
        self.elements = Array(repeating: repeatedValue, count: count)
    }
    /// Compute the contiguous storage index from high-dimensional tensor
    /// indices
    /// - parameter indices: tensor indices
    /// - returns: index in contiguous storage
    /// - note: the count of indices must equal the rank of the tensor
    public func contiguousIndex(in shape: TensorShape) -> Int {
        /// Row-major order addressing
        let trimmedShape = shape.prefix(count)
        return elements.enumerated().reduce(0, { acc, next -> Int in
            let stride = trimmedShape.isEmpty
                ? 0 : trimmedShape.dropFirst(next.offset+1).reduce(1, *)
            return acc + next.element * stride
        })
    }
}
// MARK: - Equatable, Comparable
extension TensorIndex : Comparable {
    public static func ==(lhs: TensorIndex, rhs: TensorIndex) -> Bool {
        return lhs.elements == rhs.elements
    }
    public static func <(lhs: TensorIndex, rhs: TensorIndex) -> Bool {
        for (x, y) in zip(lhs.elements, rhs.elements) {
            /// Less-than at a higher dimension => true
            if x < y { return true }
            /// Greater-than at a higher dimension => false
            if x > y { return false }
            /// Otherwise, at the same higher dimension => continue
        }
        return false
    }
}
// MARK: - RandomAccessCollection
extension TensorIndex : RandomAccessCollection {
    public var count: Int {
        return elements.count
    }
    public var dimension: Int {
        return count - 1
    }
    public subscript(bounds: Range<Int>) -> TensorIndex {
        get {
            return TensorIndex(elements[bounds])
        }
        set {
            elements[bounds] = ArraySlice(newValue.elements)
        }
    }
    public var indices: CountableRange<Int> {
        return elements.indices
    }
    public func index(after i: Int) -> Int {
        return elements.index(after: i)
    }
    public func index(before i: Int) -> Int {
        return elements.index(before: i)
    }
    public var startIndex: Int {
        return elements.startIndex
    }
    public var endIndex: Int {
        return elements.endIndex
    }
    /// Size of i-th dimension
    /// - parameter i: dimension
    public subscript(i: Int) -> Int {
        get {
            return elements[i]
        }
        set {
            elements[i] = newValue
        }
    }
}
// MARK: - Strideable
extension TensorIndex : Strideable {
    public typealias Stride = Int
    /// Returns a `Self` `x` such that `self.distance(to: x)` approximates `n`.
    ///
    /// If `Stride` conforms to `Integer`, then `self.distance(to: x) == n`.
    ///
    /// - Complexity: O(1).
    public func advanced(by n: Int) -> TensorIndex {
        guard !isEmpty else { return self }
        var newIndex = self
        newIndex[newIndex.endIndex-1] += n
        return newIndex
    }
    /// Returns a stride `x` such that `self.advanced(by: x)` approximates
    /// `other`.
    ///
    /// If `Stride` conforms to `Integer`, then `self.advanced(by: x) == other`.
    ///
    /// - Complexity: O(1).
    public func distance(to other: TensorIndex) -> Int {
        precondition(count == other.count,
                     "Indices are not in the same dimension")
        guard let otherLast = other.last, let selfLast = last else { return 0 }
        return otherLast - selfLast
    }
}
public extension TensorShape {
    /// Returns the row-major order index for the specified tensor index
    /// - parameter index: tensor index
    func contiguousIndex(for index: TensorIndex) -> Int {
        return index.contiguousIndex(in: self)
    }
    /// Returns the shape after indexing
    subscript(index: TensorIndex) -> TensorShape? {
        guard index.count < rank else {
            return nil
        }
        return dropFirst(index.count)
    }
}
 | 
	apache-2.0 | 
| 
	ubclaunchpad/RocketCast | 
	RocketCast/PodcastViewCollectionViewCell.swift | 
	1 | 
	2256 | 
	//
//  PodcastViewCollectionViewCell.swift
//  RocketCast
//
//  Created by Milton Leung on 2016-11-09.
//  Copyright © 2016 UBCLaunchPad. All rights reserved.
//
import UIKit
class PodcastViewCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var coverPhotoView: UIView!
    @IBOutlet weak var podcastTitle: UILabel!
    @IBOutlet weak var podcastAuthor: UILabel!
    
    @IBOutlet weak var photoWidth: NSLayoutConstraint!
    @IBOutlet weak var photoHeight: NSLayoutConstraint!
    var podcast: Podcast! {
        didSet {
            podcastTitle.text = podcast.title
            podcastAuthor.text = podcast.author
            let url = URL(string: (podcast.imageURL)!)
            DispatchQueue.global().async {
                do {
                    let data = try Data(contentsOf: url!)
                    let coverPhoto = UIImageView()
                    coverPhoto.frame = self.coverPhotoView.bounds
                    coverPhoto.layer.cornerRadius = 18
                    coverPhoto.layer.masksToBounds = true
                    DispatchQueue.main.async {
                        coverPhoto.image = UIImage(data: data)
                        self.coverPhotoView.addSubview(coverPhoto)
                    }
                    
                } catch let error as NSError{
                    Log.error("Error: " + error.debugDescription)
                }
            }
        }
    }
    
    var size: Int! {
        didSet {
            photoWidth.constant = CGFloat(size)
            photoHeight.constant = CGFloat(size)
        }
    }
    
    func setStyling() {
        let effectsLayer = coverPhotoView.layer
        effectsLayer.cornerRadius = 14
        effectsLayer.shadowColor = UIColor.black.cgColor
        effectsLayer.shadowOffset = CGSize(width: 0, height: 0)
        effectsLayer.shadowRadius = 4
        effectsLayer.shadowOpacity = 0.4
        effectsLayer.shadowPath = UIBezierPath(roundedRect: CGRect(x:coverPhotoView.frame.origin.x, y:coverPhotoView.frame.origin.y, width: photoWidth.constant, height:photoHeight.constant), cornerRadius: coverPhotoView.layer.cornerRadius).cgPath
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
}
 | 
	mit | 
| 
	JudoPay/JudoKit | 
	Source/NSTimer+Blocks.swift | 
	3 | 
	1879 | 
	//
//  NSTimer+Blocks.swift
//  JudoKit
//
//  Copyright © 2016 Alternative Payments Ltd. 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 Foundation
extension Timer {
    /**
     Creates and schedules a one-time `NSTimer` instance.
     
     - Parameter delay: The delay before execution.
     - Parameter handler: A closure to execute after `delay`.
     
     - Returns: The newly-created `NSTimer` instance.
     */
    class func schedule(_ delay: TimeInterval, handler: @escaping (CFRunLoopTimer?) -> Void) -> CFRunLoopTimer {
        let fireDate = delay + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
        return timer!
    }
}
 | 
	mit | 
| 
	nostramap/nostra-sdk-sample-ios | 
	SearchSample/Swift/SearchSample/KeywordViewController.swift | 
	1 | 
	2607 | 
	//
//  KeywordViewcontroller.swift
//  SearchSample
//
//  Copyright © 2559 Globtech. All rights reserved.
//
import UIKit
import NOSTRASDK
class KeywordViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var searchBar: UISearchBar!
    
    
    var keywords: [NTAutocompleteResult]?;
    
    var param: NTAutocompleteParameter?;
    
    override func viewDidLoad() {
        super.viewDidLoad();
    }
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "keywordtoResultSegue" {
            let resultViewController = segue.destination as! ResultViewController;
            
            resultViewController.searchByKeyword(sender as? String);
        }
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
        if searchText.characters.count > 0 {
            param = NTAutocompleteParameter(keyword: searchText);
            
            NTAutocompleteService.executeAsync(param!) { (resultSet, error) in
                
                DispatchQueue.main.async(execute: {
                    if error == nil {
                        self.keywords = resultSet?.results;
                    }
                    else {
                        self.keywords = [];
                        print("error: \(error?.description)");
                    }
                    self.tableView.reloadData();
                })
                
            }
        }
        
        
        
        
    }
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder();
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let keyword = keywords![indexPath.row];
        self.performSegue(withIdentifier: "keywordtoResultSegue", sender: keyword.name);
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell");
        let keyword = keywords![indexPath.row];
        
        cell?.textLabel?.text = keyword.name;
        
        return cell!;
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return keywords != nil ? (keywords?.count)! : 0;
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    
    
}
 | 
	apache-2.0 | 
| 
	rudkx/swift | 
	test/Interop/Cxx/class/constructors-irgen.swift | 
	1 | 
	9488 | 
	// Target-specific tests for C++ constructor call code generation.
// RUN: %swift -module-name Swift -target x86_64-apple-macosx10.9 -dump-clang-diagnostics -I %S/Inputs -enable-cxx-interop -emit-ir %s -parse-stdlib -parse-as-library -disable-legacy-type-info | %FileCheck %s -check-prefix=ITANIUM_X64
// RUN: %swift -module-name Swift -target armv7-unknown-linux-androideabi -dump-clang-diagnostics -I %S/Inputs -enable-cxx-interop -emit-ir %s -parse-stdlib -parse-as-library -disable-legacy-type-info | %FileCheck %s -check-prefix=ITANIUM_ARM
// RUN: %swift -module-name Swift -target x86_64-unknown-windows-msvc -dump-clang-diagnostics -I %S/Inputs -enable-cxx-interop -emit-ir %s -parse-stdlib -parse-as-library -disable-legacy-type-info | %FileCheck %s -check-prefix=MICROSOFT_X64
import Constructors
import TypeClassification
typealias Void = ()
struct UnsafePointer<T> { }
struct UnsafeMutablePointer<T> { }
struct Int { }
struct UInt { }
public func createHasVirtualBase() -> HasVirtualBase {
  // ITANIUM_X64: define swiftcc void @"$ss20createHasVirtualBaseSo0bcD0VyF"(%TSo14HasVirtualBaseV* noalias nocapture sret({{.*}}) %0)
  // ITANIUM_X64-NOT: define
  // ITANIUM_X64: call void @_ZN14HasVirtualBaseC1E7ArgType(%struct.HasVirtualBase* %{{[0-9]+}}, i32 %{{[0-9]+}})
  //
  // ITANIUM_ARM: define protected swiftcc void @"$ss20createHasVirtualBaseSo0bcD0VyF"(%TSo14HasVirtualBaseV* noalias nocapture sret({{.*}}) %0)
  // To verify that the thunk is inlined, make sure there's no intervening
  // `define`, i.e. the call to the C++ constructor happens in
  // createHasVirtualBase(), not some later function.
  // ITANIUM_ARM-NOT: define
  // Note `this` return type.
  // ITANIUM_ARM: call %struct.HasVirtualBase* @_ZN14HasVirtualBaseC1E7ArgType(%struct.HasVirtualBase* %{{[0-9]+}}, [1 x i32] %{{[0-9]+}})
  //
  // MICROSOFT_X64: define dllexport swiftcc void @"$ss20createHasVirtualBaseSo0bcD0VyF"(%TSo14HasVirtualBaseV* noalias nocapture sret({{.*}}) %0)
  // MICROSOFT_X64-NOT: define
  // Note `this` return type and implicit "most derived" argument.
  // MICROSOFT_X64: call %struct.HasVirtualBase* @"??0HasVirtualBase@@QEAA@UArgType@@@Z"(%struct.HasVirtualBase* %{{[0-9]+}}, i32 %{{[0-9]+}}, i32 1)
  return HasVirtualBase(ArgType())
}
public func createImplicitDefaultConstructor() -> ImplicitDefaultConstructor {
  // ITANIUM_X64: define swiftcc i32 @"$ss32createImplicitDefaultConstructorSo0bcD0VyF"()
  // ITANIUM_X64-NOT: define
  // ITANIUM_X64: call void @_ZN26ImplicitDefaultConstructorC1Ev(%struct.ImplicitDefaultConstructor* %{{[0-9]+}})
  //
  // ITANIUM_ARM: define protected swiftcc i32 @"$ss32createImplicitDefaultConstructorSo0bcD0VyF"()
  // ITANIUM_ARM-NOT: define
  // Note `this` return type.
  // ITANIUM_ARM: call %struct.ImplicitDefaultConstructor* @_ZN26ImplicitDefaultConstructorC2Ev(%struct.ImplicitDefaultConstructor* %{{[0-9]+}})
  //
  // MICROSOFT_X64: define dllexport swiftcc i32 @"$ss32createImplicitDefaultConstructorSo0bcD0VyF"()
  // MICROSOFT_X64-NOT: define
  // Note `this` return type but no implicit "most derived" argument.
  // MICROSOFT_X64: call %struct.ImplicitDefaultConstructor* @"??0ImplicitDefaultConstructor@@QEAA@XZ"(%struct.ImplicitDefaultConstructor* %{{[0-9]+}})
  return ImplicitDefaultConstructor()
}
public func createStructWithSubobjectCopyConstructorAndValue() {
  // ITANIUM_X64-LABEL: define swiftcc void @"$ss48createStructWithSubobjectCopyConstructorAndValueyyF"()
  // ITANIUM_X64: [[MEMBER:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV
  // ITANIUM_X64: [[OBJ:%.*]] = alloca %TSo42StructWithSubobjectCopyConstructorAndValueV
  // ITANIUM_X64: [[TMP:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV
  // ITANIUM_X64: [[MEMBER_AS_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue*
  // ITANIUM_X64: void @_ZN33StructWithCopyConstructorAndValueC1Ev(%struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT]])
  // ITANIUM_X64: [[TMP_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[TMP]] to %struct.StructWithCopyConstructorAndValue*
  // ITANIUM_X64: [[MEMBER_AS_STRUCT_2:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue*
  // ITANIUM_X64: call void @_ZN33StructWithCopyConstructorAndValueC1ERKS_(%struct.StructWithCopyConstructorAndValue* [[TMP_STRUCT]], %struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT_2]])
  // ITANIUM_X64: ret void
  
  // ITANIUM_ARM-LABEL: define protected swiftcc void @"$ss48createStructWithSubobjectCopyConstructorAndValueyyF"()
  // ITANIUM_ARM: [[MEMBER:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV
  // ITANIUM_ARM: [[OBJ:%.*]] = alloca %TSo42StructWithSubobjectCopyConstructorAndValueV
  // ITANIUM_ARM: [[TMP:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV
  // ITANIUM_ARM: [[MEMBER_AS_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue*
  // ITANIUM_ARM: call %struct.StructWithCopyConstructorAndValue* @_ZN33StructWithCopyConstructorAndValueC2Ev(%struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT]])
  // ITANIUM_ARM: [[TMP_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[TMP]] to %struct.StructWithCopyConstructorAndValue*
  // ITANIUM_ARM: [[MEMBER_AS_STRUCT_2:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue*
  // ITANIUM_ARM: call %struct.StructWithCopyConstructorAndValue* @_ZN33StructWithCopyConstructorAndValueC2ERKS_(%struct.StructWithCopyConstructorAndValue* [[TMP_STRUCT]], %struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT_2]])
  // ITANIUM_ARM: ret void
  // MICROSOFT_X64-LABEL: define dllexport swiftcc void @"$ss48createStructWithSubobjectCopyConstructorAndValueyyF"()
  // MICROSOFT_X64: [[MEMBER:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV
  // MICROSOFT_X64: [[OBJ:%.*]] = alloca %TSo42StructWithSubobjectCopyConstructorAndValueV
  // MICROSOFT_X64: [[TMP:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV
  // MICROSOFT_X64: [[MEMBER_AS_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue*
  // MICROSOFT_X64: call %struct.StructWithCopyConstructorAndValue* @"??0StructWithCopyConstructorAndValue@@QEAA@XZ"(%struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT]])
  // MICROSOFT_X64: [[TMP_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[TMP]] to %struct.StructWithCopyConstructorAndValue*
  // MICROSOFT_X64: [[MEMBER_AS_STRUCT_2:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue*
  // MICROSOFT_X64: call %struct.StructWithCopyConstructorAndValue* @"??0StructWithCopyConstructorAndValue@@QEAA@AEBU0@@Z"(%struct.StructWithCopyConstructorAndValue* [[TMP_STRUCT]], %struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT_2]])
  // MICROSOFT_X64: ret void
  let member = StructWithCopyConstructorAndValue()
  let obj = StructWithSubobjectCopyConstructorAndValue(member: member)
}
public func createTemplatedConstructor() {
  // ITANIUM_X64-LABEL: define swiftcc void @"$ss26createTemplatedConstructoryyF"()
  // ITANIUM_X64: [[OBJ:%.*]] = alloca %TSo20TemplatedConstructorV
  // ITANIUM_X64: [[IVAL:%.*]] = load i32, i32*
  // ITANIUM_X64: [[OBJ_AS_STRUCT:%.*]] = bitcast %TSo20TemplatedConstructorV* [[OBJ]] to %struct.TemplatedConstructor*
  // ITANIUM_X64: call void @_ZN20TemplatedConstructorC1I7ArgTypeEET_(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], i32 [[IVAL]])
  // ITANIUM_X64: ret void
  
  // ITANIUM_X64-LABEL: define linkonce_odr void @_ZN20TemplatedConstructorC1I7ArgTypeEET_(%struct.TemplatedConstructor* nonnull align 4 dereferenceable(4) {{.*}}, i32 {{.*}})
  
  // ITANIUM_ARM-LABEL: define protected swiftcc void @"$ss26createTemplatedConstructoryyF"()
  // ITANIUM_ARM: [[OBJ:%.*]] = alloca %TSo20TemplatedConstructorV
  // ITANIUM_ARM: [[IVAL:%.*]] = load [1 x i32], [1 x i32]*
  // ITANIUM_ARM: [[OBJ_AS_STRUCT:%.*]] = bitcast %TSo20TemplatedConstructorV* [[OBJ]] to %struct.TemplatedConstructor*
  // ITANIUM_ARM:  call %struct.TemplatedConstructor* @_ZN20TemplatedConstructorC2I7ArgTypeEET_(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], [1 x i32] [[IVAL]])
  // ITANIUM_ARM: ret void
  
  // ITANIUM_ARM-LABEL: define linkonce_odr %struct.TemplatedConstructor* @_ZN20TemplatedConstructorC2I7ArgTypeEET_(%struct.TemplatedConstructor* nonnull returned align 4 dereferenceable(4) {{.*}}, [1 x i32] {{.*}})
  // MICROSOFT_X64-LABEL: define dllexport swiftcc void @"$ss26createTemplatedConstructoryyF"()
  // MICROSOFT_X64: [[OBJ:%.*]] = alloca %TSo20TemplatedConstructorV
  // MICROSOFT_X64: [[IVAL:%.*]] = load i32, i32*
  // MICROSOFT_X64: [[OBJ_AS_STRUCT:%.*]] = bitcast %TSo20TemplatedConstructorV* [[OBJ]] to %struct.TemplatedConstructor*
  // MICROSOFT_X64: call %struct.TemplatedConstructor* @"??$?0UArgType@@@TemplatedConstructor@@QEAA@UArgType@@@Z"(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], i32 [[IVAL]])
  // MICROSOFT_X64: ret void
  
  // MICROSOFT_X64-LABEL: define linkonce_odr dso_local %struct.TemplatedConstructor* @"??$?0UArgType@@@TemplatedConstructor@@QEAA@UArgType@@@Z"(%struct.TemplatedConstructor* nonnull returned align 4 dereferenceable(4) {{.*}}, i32 {{.*}})
  let templated = TemplatedConstructor(ArgType())
}
 | 
	apache-2.0 | 
| 
	WebberLai/WLComics | 
	Pods/SwiftyDropbox/Source/SwiftyDropbox/Shared/Generated/Files.swift | 
	1 | 
	339473 | 
	///
/// Copyright (c) 2016 Dropbox, Inc. All rights reserved.
///
/// Auto-generated by Stone, do not modify.
///
import Foundation
/// Datatypes and serializers for the files namespace
open class Files {
    /// The GetMetadataArg struct
    open class GetMetadataArg: CustomStringConvertible {
        /// The path of a file or folder on Dropbox.
        public let path: String
        /// If true, mediaInfo in FileMetadata is set for photo and video.
        public let includeMediaInfo: Bool
        /// If true, DeletedMetadata will be returned for deleted file or folder, otherwise notFound in LookupError will
        /// be returned.
        public let includeDeleted: Bool
        /// If true, the results will include a flag for each file indicating whether or not  that file has any explicit
        /// members.
        public let includeHasExplicitSharedMembers: Bool
        /// If set to a valid list of template IDs, propertyGroups in FileMetadata is set if there exists property data
        /// associated with the file and each of the listed templates.
        public let includePropertyGroups: FileProperties.TemplateFilterBase?
        public init(path: String, includeMediaInfo: Bool = false, includeDeleted: Bool = false, includeHasExplicitSharedMembers: Bool = false, includePropertyGroups: FileProperties.TemplateFilterBase? = nil) {
            stringValidator(pattern: "(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            self.includeMediaInfo = includeMediaInfo
            self.includeDeleted = includeDeleted
            self.includeHasExplicitSharedMembers = includeHasExplicitSharedMembers
            self.includePropertyGroups = includePropertyGroups
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetMetadataArgSerializer().serialize(self)))"
        }
    }
    open class GetMetadataArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetMetadataArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "include_media_info": Serialization._BoolSerializer.serialize(value.includeMediaInfo),
            "include_deleted": Serialization._BoolSerializer.serialize(value.includeDeleted),
            "include_has_explicit_shared_members": Serialization._BoolSerializer.serialize(value.includeHasExplicitSharedMembers),
            "include_property_groups": NullableSerializer(FileProperties.TemplateFilterBaseSerializer()).serialize(value.includePropertyGroups),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetMetadataArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let includeMediaInfo = Serialization._BoolSerializer.deserialize(dict["include_media_info"] ?? .number(0))
                    let includeDeleted = Serialization._BoolSerializer.deserialize(dict["include_deleted"] ?? .number(0))
                    let includeHasExplicitSharedMembers = Serialization._BoolSerializer.deserialize(dict["include_has_explicit_shared_members"] ?? .number(0))
                    let includePropertyGroups = NullableSerializer(FileProperties.TemplateFilterBaseSerializer()).deserialize(dict["include_property_groups"] ?? .null)
                    return GetMetadataArg(path: path, includeMediaInfo: includeMediaInfo, includeDeleted: includeDeleted, includeHasExplicitSharedMembers: includeHasExplicitSharedMembers, includePropertyGroups: includePropertyGroups)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The AlphaGetMetadataArg struct
    open class AlphaGetMetadataArg: Files.GetMetadataArg {
        /// If set to a valid list of template IDs, propertyGroups in FileMetadata is set for files with custom
        /// properties.
        public let includePropertyTemplates: Array<String>?
        public init(path: String, includeMediaInfo: Bool = false, includeDeleted: Bool = false, includeHasExplicitSharedMembers: Bool = false, includePropertyGroups: FileProperties.TemplateFilterBase? = nil, includePropertyTemplates: Array<String>? = nil) {
            nullableValidator(arrayValidator(itemValidator: stringValidator(minLength: 1, pattern: "(/|ptid:).*")))(includePropertyTemplates)
            self.includePropertyTemplates = includePropertyTemplates
            super.init(path: path, includeMediaInfo: includeMediaInfo, includeDeleted: includeDeleted, includeHasExplicitSharedMembers: includeHasExplicitSharedMembers, includePropertyGroups: includePropertyGroups)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(AlphaGetMetadataArgSerializer().serialize(self)))"
        }
    }
    open class AlphaGetMetadataArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: AlphaGetMetadataArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "include_media_info": Serialization._BoolSerializer.serialize(value.includeMediaInfo),
            "include_deleted": Serialization._BoolSerializer.serialize(value.includeDeleted),
            "include_has_explicit_shared_members": Serialization._BoolSerializer.serialize(value.includeHasExplicitSharedMembers),
            "include_property_groups": NullableSerializer(FileProperties.TemplateFilterBaseSerializer()).serialize(value.includePropertyGroups),
            "include_property_templates": NullableSerializer(ArraySerializer(Serialization._StringSerializer)).serialize(value.includePropertyTemplates),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> AlphaGetMetadataArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let includeMediaInfo = Serialization._BoolSerializer.deserialize(dict["include_media_info"] ?? .number(0))
                    let includeDeleted = Serialization._BoolSerializer.deserialize(dict["include_deleted"] ?? .number(0))
                    let includeHasExplicitSharedMembers = Serialization._BoolSerializer.deserialize(dict["include_has_explicit_shared_members"] ?? .number(0))
                    let includePropertyGroups = NullableSerializer(FileProperties.TemplateFilterBaseSerializer()).deserialize(dict["include_property_groups"] ?? .null)
                    let includePropertyTemplates = NullableSerializer(ArraySerializer(Serialization._StringSerializer)).deserialize(dict["include_property_templates"] ?? .null)
                    return AlphaGetMetadataArg(path: path, includeMediaInfo: includeMediaInfo, includeDeleted: includeDeleted, includeHasExplicitSharedMembers: includeHasExplicitSharedMembers, includePropertyGroups: includePropertyGroups, includePropertyTemplates: includePropertyTemplates)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetMetadataError union
    public enum GetMetadataError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetMetadataErrorSerializer().serialize(self)))"
        }
    }
    open class GetMetadataErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetMetadataError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> GetMetadataError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return GetMetadataError.path(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The AlphaGetMetadataError union
    public enum AlphaGetMetadataError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// An unspecified error.
        case propertiesError(FileProperties.LookUpPropertiesError)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(AlphaGetMetadataErrorSerializer().serialize(self)))"
        }
    }
    open class AlphaGetMetadataErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: AlphaGetMetadataError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .propertiesError(let arg):
                    var d = ["properties_error": FileProperties.LookUpPropertiesErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("properties_error")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> AlphaGetMetadataError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return AlphaGetMetadataError.path(v)
                        case "properties_error":
                            let v = FileProperties.LookUpPropertiesErrorSerializer().deserialize(d["properties_error"] ?? .null)
                            return AlphaGetMetadataError.propertiesError(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The CommitInfo struct
    open class CommitInfo: CustomStringConvertible {
        /// Path in the user's Dropbox to save the file.
        public let path: String
        /// Selects what to do if the file already exists.
        public let mode: Files.WriteMode
        /// If there's a conflict, as determined by mode, have the Dropbox server try to autorename the file to avoid
        /// conflict.
        public let autorename: Bool
        /// The value to store as the clientModified timestamp. Dropbox automatically records the time at which the file
        /// was written to the Dropbox servers. It can also record an additional timestamp, provided by Dropbox desktop
        /// clients, mobile clients, and API apps of when the file was actually created or modified.
        public let clientModified: Date?
        /// Normally, users are made aware of any file modifications in their Dropbox account via notifications in the
        /// client software. If true, this tells the clients that this modification shouldn't result in a user
        /// notification.
        public let mute: Bool
        /// List of custom properties to add to file.
        public let propertyGroups: Array<FileProperties.PropertyGroup>?
        /// Be more strict about how each WriteMode detects conflict. For example, always return a conflict error when
        /// mode = update in WriteMode and the given "rev" doesn't match the existing file's "rev", even if the existing
        /// file has been deleted.
        public let strictConflict: Bool
        public init(path: String, mode: Files.WriteMode = .add, autorename: Bool = false, clientModified: Date? = nil, mute: Bool = false, propertyGroups: Array<FileProperties.PropertyGroup>? = nil, strictConflict: Bool = false) {
            stringValidator(pattern: "(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)|(id:.*)")(path)
            self.path = path
            self.mode = mode
            self.autorename = autorename
            self.clientModified = clientModified
            self.mute = mute
            self.propertyGroups = propertyGroups
            self.strictConflict = strictConflict
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CommitInfoSerializer().serialize(self)))"
        }
    }
    open class CommitInfoSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CommitInfo) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "mode": Files.WriteModeSerializer().serialize(value.mode),
            "autorename": Serialization._BoolSerializer.serialize(value.autorename),
            "client_modified": NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).serialize(value.clientModified),
            "mute": Serialization._BoolSerializer.serialize(value.mute),
            "property_groups": NullableSerializer(ArraySerializer(FileProperties.PropertyGroupSerializer())).serialize(value.propertyGroups),
            "strict_conflict": Serialization._BoolSerializer.serialize(value.strictConflict),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> CommitInfo {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let mode = Files.WriteModeSerializer().deserialize(dict["mode"] ?? Files.WriteModeSerializer().serialize(.add))
                    let autorename = Serialization._BoolSerializer.deserialize(dict["autorename"] ?? .number(0))
                    let clientModified = NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).deserialize(dict["client_modified"] ?? .null)
                    let mute = Serialization._BoolSerializer.deserialize(dict["mute"] ?? .number(0))
                    let propertyGroups = NullableSerializer(ArraySerializer(FileProperties.PropertyGroupSerializer())).deserialize(dict["property_groups"] ?? .null)
                    let strictConflict = Serialization._BoolSerializer.deserialize(dict["strict_conflict"] ?? .number(0))
                    return CommitInfo(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute, propertyGroups: propertyGroups, strictConflict: strictConflict)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The CommitInfoWithProperties struct
    open class CommitInfoWithProperties: Files.CommitInfo {
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CommitInfoWithPropertiesSerializer().serialize(self)))"
        }
    }
    open class CommitInfoWithPropertiesSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CommitInfoWithProperties) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "mode": Files.WriteModeSerializer().serialize(value.mode),
            "autorename": Serialization._BoolSerializer.serialize(value.autorename),
            "client_modified": NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).serialize(value.clientModified),
            "mute": Serialization._BoolSerializer.serialize(value.mute),
            "property_groups": NullableSerializer(ArraySerializer(FileProperties.PropertyGroupSerializer())).serialize(value.propertyGroups),
            "strict_conflict": Serialization._BoolSerializer.serialize(value.strictConflict),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> CommitInfoWithProperties {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let mode = Files.WriteModeSerializer().deserialize(dict["mode"] ?? Files.WriteModeSerializer().serialize(.add))
                    let autorename = Serialization._BoolSerializer.deserialize(dict["autorename"] ?? .number(0))
                    let clientModified = NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).deserialize(dict["client_modified"] ?? .null)
                    let mute = Serialization._BoolSerializer.deserialize(dict["mute"] ?? .number(0))
                    let propertyGroups = NullableSerializer(ArraySerializer(FileProperties.PropertyGroupSerializer())).deserialize(dict["property_groups"] ?? .null)
                    let strictConflict = Serialization._BoolSerializer.deserialize(dict["strict_conflict"] ?? .number(0))
                    return CommitInfoWithProperties(path: path, mode: mode, autorename: autorename, clientModified: clientModified, mute: mute, propertyGroups: propertyGroups, strictConflict: strictConflict)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ContentSyncSetting struct
    open class ContentSyncSetting: CustomStringConvertible {
        /// Id of the item this setting is applied to.
        public let id: String
        /// Setting for this item.
        public let syncSetting: Files.SyncSetting
        public init(id: String, syncSetting: Files.SyncSetting) {
            stringValidator(minLength: 4, pattern: "id:.+")(id)
            self.id = id
            self.syncSetting = syncSetting
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ContentSyncSettingSerializer().serialize(self)))"
        }
    }
    open class ContentSyncSettingSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ContentSyncSetting) -> JSON {
            let output = [ 
            "id": Serialization._StringSerializer.serialize(value.id),
            "sync_setting": Files.SyncSettingSerializer().serialize(value.syncSetting),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ContentSyncSetting {
            switch json {
                case .dictionary(let dict):
                    let id = Serialization._StringSerializer.deserialize(dict["id"] ?? .null)
                    let syncSetting = Files.SyncSettingSerializer().deserialize(dict["sync_setting"] ?? .null)
                    return ContentSyncSetting(id: id, syncSetting: syncSetting)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ContentSyncSettingArg struct
    open class ContentSyncSettingArg: CustomStringConvertible {
        /// Id of the item this setting is applied to.
        public let id: String
        /// Setting for this item.
        public let syncSetting: Files.SyncSettingArg
        public init(id: String, syncSetting: Files.SyncSettingArg) {
            stringValidator(minLength: 4, pattern: "id:.+")(id)
            self.id = id
            self.syncSetting = syncSetting
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ContentSyncSettingArgSerializer().serialize(self)))"
        }
    }
    open class ContentSyncSettingArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ContentSyncSettingArg) -> JSON {
            let output = [ 
            "id": Serialization._StringSerializer.serialize(value.id),
            "sync_setting": Files.SyncSettingArgSerializer().serialize(value.syncSetting),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ContentSyncSettingArg {
            switch json {
                case .dictionary(let dict):
                    let id = Serialization._StringSerializer.deserialize(dict["id"] ?? .null)
                    let syncSetting = Files.SyncSettingArgSerializer().deserialize(dict["sync_setting"] ?? .null)
                    return ContentSyncSettingArg(id: id, syncSetting: syncSetting)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The CreateFolderArg struct
    open class CreateFolderArg: CustomStringConvertible {
        /// Path in the user's Dropbox to create.
        public let path: String
        /// If there's a conflict, have the Dropbox server try to autorename the folder to avoid the conflict.
        public let autorename: Bool
        public init(path: String, autorename: Bool = false) {
            stringValidator(pattern: "(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            self.autorename = autorename
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderArgSerializer().serialize(self)))"
        }
    }
    open class CreateFolderArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "autorename": Serialization._BoolSerializer.serialize(value.autorename),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> CreateFolderArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let autorename = Serialization._BoolSerializer.deserialize(dict["autorename"] ?? .number(0))
                    return CreateFolderArg(path: path, autorename: autorename)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The CreateFolderBatchArg struct
    open class CreateFolderBatchArg: CustomStringConvertible {
        /// List of paths to be created in the user's Dropbox. Duplicate path arguments in the batch are considered only
        /// once.
        public let paths: Array<String>
        /// If there's a conflict, have the Dropbox server try to autorename the folder to avoid the conflict.
        public let autorename: Bool
        /// Whether to force the create to happen asynchronously.
        public let forceAsync: Bool
        public init(paths: Array<String>, autorename: Bool = false, forceAsync: Bool = false) {
            arrayValidator(itemValidator: stringValidator(pattern: "(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)"))(paths)
            self.paths = paths
            self.autorename = autorename
            self.forceAsync = forceAsync
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderBatchArgSerializer().serialize(self)))"
        }
    }
    open class CreateFolderBatchArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderBatchArg) -> JSON {
            let output = [ 
            "paths": ArraySerializer(Serialization._StringSerializer).serialize(value.paths),
            "autorename": Serialization._BoolSerializer.serialize(value.autorename),
            "force_async": Serialization._BoolSerializer.serialize(value.forceAsync),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> CreateFolderBatchArg {
            switch json {
                case .dictionary(let dict):
                    let paths = ArraySerializer(Serialization._StringSerializer).deserialize(dict["paths"] ?? .null)
                    let autorename = Serialization._BoolSerializer.deserialize(dict["autorename"] ?? .number(0))
                    let forceAsync = Serialization._BoolSerializer.deserialize(dict["force_async"] ?? .number(0))
                    return CreateFolderBatchArg(paths: paths, autorename: autorename, forceAsync: forceAsync)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The CreateFolderBatchError union
    public enum CreateFolderBatchError: CustomStringConvertible {
        /// The operation would involve too many files or folders.
        case tooManyFiles
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderBatchErrorSerializer().serialize(self)))"
        }
    }
    open class CreateFolderBatchErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderBatchError) -> JSON {
            switch value {
                case .tooManyFiles:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_files")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> CreateFolderBatchError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "too_many_files":
                            return CreateFolderBatchError.tooManyFiles
                        case "other":
                            return CreateFolderBatchError.other
                        default:
                            return CreateFolderBatchError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The CreateFolderBatchJobStatus union
    public enum CreateFolderBatchJobStatus: CustomStringConvertible {
        /// The asynchronous job is still in progress.
        case inProgress
        /// The batch create folder has finished.
        case complete(Files.CreateFolderBatchResult)
        /// The batch create folder has failed.
        case failed(Files.CreateFolderBatchError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderBatchJobStatusSerializer().serialize(self)))"
        }
    }
    open class CreateFolderBatchJobStatusSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderBatchJobStatus) -> JSON {
            switch value {
                case .inProgress:
                    var d = [String: JSON]()
                    d[".tag"] = .str("in_progress")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.CreateFolderBatchResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
                case .failed(let arg):
                    var d = ["failed": Files.CreateFolderBatchErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("failed")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> CreateFolderBatchJobStatus {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "in_progress":
                            return CreateFolderBatchJobStatus.inProgress
                        case "complete":
                            let v = Files.CreateFolderBatchResultSerializer().deserialize(json)
                            return CreateFolderBatchJobStatus.complete(v)
                        case "failed":
                            let v = Files.CreateFolderBatchErrorSerializer().deserialize(d["failed"] ?? .null)
                            return CreateFolderBatchJobStatus.failed(v)
                        case "other":
                            return CreateFolderBatchJobStatus.other
                        default:
                            return CreateFolderBatchJobStatus.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Result returned by createFolderBatch that may either launch an asynchronous job or complete synchronously.
    public enum CreateFolderBatchLaunch: CustomStringConvertible {
        /// This response indicates that the processing is asynchronous. The string is an id that can be used to obtain
        /// the status of the asynchronous job.
        case asyncJobId(String)
        /// An unspecified error.
        case complete(Files.CreateFolderBatchResult)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderBatchLaunchSerializer().serialize(self)))"
        }
    }
    open class CreateFolderBatchLaunchSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderBatchLaunch) -> JSON {
            switch value {
                case .asyncJobId(let arg):
                    var d = ["async_job_id": Serialization._StringSerializer.serialize(arg)]
                    d[".tag"] = .str("async_job_id")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.CreateFolderBatchResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> CreateFolderBatchLaunch {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "async_job_id":
                            let v = Serialization._StringSerializer.deserialize(d["async_job_id"] ?? .null)
                            return CreateFolderBatchLaunch.asyncJobId(v)
                        case "complete":
                            let v = Files.CreateFolderBatchResultSerializer().deserialize(json)
                            return CreateFolderBatchLaunch.complete(v)
                        case "other":
                            return CreateFolderBatchLaunch.other
                        default:
                            return CreateFolderBatchLaunch.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The FileOpsResult struct
    open class FileOpsResult: CustomStringConvertible {
        public init() {
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(FileOpsResultSerializer().serialize(self)))"
        }
    }
    open class FileOpsResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: FileOpsResult) -> JSON {
            let output = [String: JSON]()
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> FileOpsResult {
            switch json {
                case .dictionary(_):
                    return FileOpsResult()
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The CreateFolderBatchResult struct
    open class CreateFolderBatchResult: Files.FileOpsResult {
        /// Each entry in paths in CreateFolderBatchArg will appear at the same position inside entries in
        /// CreateFolderBatchResult.
        public let entries: Array<Files.CreateFolderBatchResultEntry>
        public init(entries: Array<Files.CreateFolderBatchResultEntry>) {
            self.entries = entries
            super.init()
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderBatchResultSerializer().serialize(self)))"
        }
    }
    open class CreateFolderBatchResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderBatchResult) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.CreateFolderBatchResultEntrySerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> CreateFolderBatchResult {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.CreateFolderBatchResultEntrySerializer()).deserialize(dict["entries"] ?? .null)
                    return CreateFolderBatchResult(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The CreateFolderBatchResultEntry union
    public enum CreateFolderBatchResultEntry: CustomStringConvertible {
        /// An unspecified error.
        case success(Files.CreateFolderEntryResult)
        /// An unspecified error.
        case failure(Files.CreateFolderEntryError)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderBatchResultEntrySerializer().serialize(self)))"
        }
    }
    open class CreateFolderBatchResultEntrySerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderBatchResultEntry) -> JSON {
            switch value {
                case .success(let arg):
                    var d = Serialization.getFields(Files.CreateFolderEntryResultSerializer().serialize(arg))
                    d[".tag"] = .str("success")
                    return .dictionary(d)
                case .failure(let arg):
                    var d = ["failure": Files.CreateFolderEntryErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("failure")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> CreateFolderBatchResultEntry {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "success":
                            let v = Files.CreateFolderEntryResultSerializer().deserialize(json)
                            return CreateFolderBatchResultEntry.success(v)
                        case "failure":
                            let v = Files.CreateFolderEntryErrorSerializer().deserialize(d["failure"] ?? .null)
                            return CreateFolderBatchResultEntry.failure(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The CreateFolderEntryError union
    public enum CreateFolderEntryError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.WriteError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderEntryErrorSerializer().serialize(self)))"
        }
    }
    open class CreateFolderEntryErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderEntryError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> CreateFolderEntryError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.WriteErrorSerializer().deserialize(d["path"] ?? .null)
                            return CreateFolderEntryError.path(v)
                        case "other":
                            return CreateFolderEntryError.other
                        default:
                            return CreateFolderEntryError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The CreateFolderEntryResult struct
    open class CreateFolderEntryResult: CustomStringConvertible {
        /// Metadata of the created folder.
        public let metadata: Files.FolderMetadata
        public init(metadata: Files.FolderMetadata) {
            self.metadata = metadata
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderEntryResultSerializer().serialize(self)))"
        }
    }
    open class CreateFolderEntryResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderEntryResult) -> JSON {
            let output = [ 
            "metadata": Files.FolderMetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> CreateFolderEntryResult {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.FolderMetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return CreateFolderEntryResult(metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The CreateFolderError union
    public enum CreateFolderError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.WriteError)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderErrorSerializer().serialize(self)))"
        }
    }
    open class CreateFolderErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> CreateFolderError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.WriteErrorSerializer().deserialize(d["path"] ?? .null)
                            return CreateFolderError.path(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The CreateFolderResult struct
    open class CreateFolderResult: Files.FileOpsResult {
        /// Metadata of the created folder.
        public let metadata: Files.FolderMetadata
        public init(metadata: Files.FolderMetadata) {
            self.metadata = metadata
            super.init()
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(CreateFolderResultSerializer().serialize(self)))"
        }
    }
    open class CreateFolderResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: CreateFolderResult) -> JSON {
            let output = [ 
            "metadata": Files.FolderMetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> CreateFolderResult {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.FolderMetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return CreateFolderResult(metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The DeleteArg struct
    open class DeleteArg: CustomStringConvertible {
        /// Path in the user's Dropbox to delete.
        public let path: String
        /// Perform delete if given "rev" matches the existing file's latest "rev". This field does not support deleting
        /// a folder.
        public let parentRev: String?
        public init(path: String, parentRev: String? = nil) {
            stringValidator(pattern: "(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)|(id:.*)")(path)
            self.path = path
            nullableValidator(stringValidator(minLength: 9, pattern: "[0-9a-f]+"))(parentRev)
            self.parentRev = parentRev
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteArgSerializer().serialize(self)))"
        }
    }
    open class DeleteArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "parent_rev": NullableSerializer(Serialization._StringSerializer).serialize(value.parentRev),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DeleteArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let parentRev = NullableSerializer(Serialization._StringSerializer).deserialize(dict["parent_rev"] ?? .null)
                    return DeleteArg(path: path, parentRev: parentRev)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The DeleteBatchArg struct
    open class DeleteBatchArg: CustomStringConvertible {
        /// (no description)
        public let entries: Array<Files.DeleteArg>
        public init(entries: Array<Files.DeleteArg>) {
            self.entries = entries
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteBatchArgSerializer().serialize(self)))"
        }
    }
    open class DeleteBatchArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteBatchArg) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.DeleteArgSerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DeleteBatchArg {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.DeleteArgSerializer()).deserialize(dict["entries"] ?? .null)
                    return DeleteBatchArg(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The DeleteBatchError union
    public enum DeleteBatchError: CustomStringConvertible {
        /// Use tooManyWriteOperations in DeleteError. deleteBatch now provides smaller granularity about which entry
        /// has failed because of this.
        case tooManyWriteOperations
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteBatchErrorSerializer().serialize(self)))"
        }
    }
    open class DeleteBatchErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteBatchError) -> JSON {
            switch value {
                case .tooManyWriteOperations:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_write_operations")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> DeleteBatchError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "too_many_write_operations":
                            return DeleteBatchError.tooManyWriteOperations
                        case "other":
                            return DeleteBatchError.other
                        default:
                            return DeleteBatchError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The DeleteBatchJobStatus union
    public enum DeleteBatchJobStatus: CustomStringConvertible {
        /// The asynchronous job is still in progress.
        case inProgress
        /// The batch delete has finished.
        case complete(Files.DeleteBatchResult)
        /// The batch delete has failed.
        case failed(Files.DeleteBatchError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteBatchJobStatusSerializer().serialize(self)))"
        }
    }
    open class DeleteBatchJobStatusSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteBatchJobStatus) -> JSON {
            switch value {
                case .inProgress:
                    var d = [String: JSON]()
                    d[".tag"] = .str("in_progress")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.DeleteBatchResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
                case .failed(let arg):
                    var d = ["failed": Files.DeleteBatchErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("failed")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> DeleteBatchJobStatus {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "in_progress":
                            return DeleteBatchJobStatus.inProgress
                        case "complete":
                            let v = Files.DeleteBatchResultSerializer().deserialize(json)
                            return DeleteBatchJobStatus.complete(v)
                        case "failed":
                            let v = Files.DeleteBatchErrorSerializer().deserialize(d["failed"] ?? .null)
                            return DeleteBatchJobStatus.failed(v)
                        case "other":
                            return DeleteBatchJobStatus.other
                        default:
                            return DeleteBatchJobStatus.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Result returned by deleteBatch that may either launch an asynchronous job or complete synchronously.
    public enum DeleteBatchLaunch: CustomStringConvertible {
        /// This response indicates that the processing is asynchronous. The string is an id that can be used to obtain
        /// the status of the asynchronous job.
        case asyncJobId(String)
        /// An unspecified error.
        case complete(Files.DeleteBatchResult)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteBatchLaunchSerializer().serialize(self)))"
        }
    }
    open class DeleteBatchLaunchSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteBatchLaunch) -> JSON {
            switch value {
                case .asyncJobId(let arg):
                    var d = ["async_job_id": Serialization._StringSerializer.serialize(arg)]
                    d[".tag"] = .str("async_job_id")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.DeleteBatchResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> DeleteBatchLaunch {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "async_job_id":
                            let v = Serialization._StringSerializer.deserialize(d["async_job_id"] ?? .null)
                            return DeleteBatchLaunch.asyncJobId(v)
                        case "complete":
                            let v = Files.DeleteBatchResultSerializer().deserialize(json)
                            return DeleteBatchLaunch.complete(v)
                        case "other":
                            return DeleteBatchLaunch.other
                        default:
                            return DeleteBatchLaunch.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The DeleteBatchResult struct
    open class DeleteBatchResult: Files.FileOpsResult {
        /// Each entry in entries in DeleteBatchArg will appear at the same position inside entries in
        /// DeleteBatchResult.
        public let entries: Array<Files.DeleteBatchResultEntry>
        public init(entries: Array<Files.DeleteBatchResultEntry>) {
            self.entries = entries
            super.init()
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteBatchResultSerializer().serialize(self)))"
        }
    }
    open class DeleteBatchResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteBatchResult) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.DeleteBatchResultEntrySerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DeleteBatchResult {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.DeleteBatchResultEntrySerializer()).deserialize(dict["entries"] ?? .null)
                    return DeleteBatchResult(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The DeleteBatchResultData struct
    open class DeleteBatchResultData: CustomStringConvertible {
        /// Metadata of the deleted object.
        public let metadata: Files.Metadata
        public init(metadata: Files.Metadata) {
            self.metadata = metadata
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteBatchResultDataSerializer().serialize(self)))"
        }
    }
    open class DeleteBatchResultDataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteBatchResultData) -> JSON {
            let output = [ 
            "metadata": Files.MetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DeleteBatchResultData {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.MetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return DeleteBatchResultData(metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The DeleteBatchResultEntry union
    public enum DeleteBatchResultEntry: CustomStringConvertible {
        /// An unspecified error.
        case success(Files.DeleteBatchResultData)
        /// An unspecified error.
        case failure(Files.DeleteError)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteBatchResultEntrySerializer().serialize(self)))"
        }
    }
    open class DeleteBatchResultEntrySerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteBatchResultEntry) -> JSON {
            switch value {
                case .success(let arg):
                    var d = Serialization.getFields(Files.DeleteBatchResultDataSerializer().serialize(arg))
                    d[".tag"] = .str("success")
                    return .dictionary(d)
                case .failure(let arg):
                    var d = ["failure": Files.DeleteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("failure")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> DeleteBatchResultEntry {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "success":
                            let v = Files.DeleteBatchResultDataSerializer().deserialize(json)
                            return DeleteBatchResultEntry.success(v)
                        case "failure":
                            let v = Files.DeleteErrorSerializer().deserialize(d["failure"] ?? .null)
                            return DeleteBatchResultEntry.failure(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The DeleteError union
    public enum DeleteError: CustomStringConvertible {
        /// An unspecified error.
        case pathLookup(Files.LookupError)
        /// An unspecified error.
        case pathWrite(Files.WriteError)
        /// There are too many write operations in user's Dropbox. Please retry this request.
        case tooManyWriteOperations
        /// There are too many files in one request. Please retry with fewer files.
        case tooManyFiles
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteErrorSerializer().serialize(self)))"
        }
    }
    open class DeleteErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteError) -> JSON {
            switch value {
                case .pathLookup(let arg):
                    var d = ["path_lookup": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path_lookup")
                    return .dictionary(d)
                case .pathWrite(let arg):
                    var d = ["path_write": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path_write")
                    return .dictionary(d)
                case .tooManyWriteOperations:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_write_operations")
                    return .dictionary(d)
                case .tooManyFiles:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_files")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> DeleteError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path_lookup":
                            let v = Files.LookupErrorSerializer().deserialize(d["path_lookup"] ?? .null)
                            return DeleteError.pathLookup(v)
                        case "path_write":
                            let v = Files.WriteErrorSerializer().deserialize(d["path_write"] ?? .null)
                            return DeleteError.pathWrite(v)
                        case "too_many_write_operations":
                            return DeleteError.tooManyWriteOperations
                        case "too_many_files":
                            return DeleteError.tooManyFiles
                        case "other":
                            return DeleteError.other
                        default:
                            return DeleteError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The DeleteResult struct
    open class DeleteResult: Files.FileOpsResult {
        /// Metadata of the deleted object.
        public let metadata: Files.Metadata
        public init(metadata: Files.Metadata) {
            self.metadata = metadata
            super.init()
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeleteResultSerializer().serialize(self)))"
        }
    }
    open class DeleteResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeleteResult) -> JSON {
            let output = [ 
            "metadata": Files.MetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DeleteResult {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.MetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return DeleteResult(metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Metadata for a file or folder.
    open class Metadata: CustomStringConvertible {
        /// The last component of the path (including extension). This never contains a slash.
        public let name: String
        /// The lowercased full path in the user's Dropbox. This always starts with a slash. This field will be null if
        /// the file or folder is not mounted.
        public let pathLower: String?
        /// The cased path to be used for display purposes only. In rare instances the casing will not correctly match
        /// the user's filesystem, but this behavior will match the path provided in the Core API v1, and at least the
        /// last path component will have the correct casing. Changes to only the casing of paths won't be returned by
        /// listFolderContinue. This field will be null if the file or folder is not mounted.
        public let pathDisplay: String?
        /// Please use parentSharedFolderId in FileSharingInfo or parentSharedFolderId in FolderSharingInfo instead.
        public let parentSharedFolderId: String?
        public init(name: String, pathLower: String? = nil, pathDisplay: String? = nil, parentSharedFolderId: String? = nil) {
            stringValidator()(name)
            self.name = name
            nullableValidator(stringValidator())(pathLower)
            self.pathLower = pathLower
            nullableValidator(stringValidator())(pathDisplay)
            self.pathDisplay = pathDisplay
            nullableValidator(stringValidator(pattern: "[-_0-9a-zA-Z:]+"))(parentSharedFolderId)
            self.parentSharedFolderId = parentSharedFolderId
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(MetadataSerializer().serialize(self)))"
        }
    }
    open class MetadataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: Metadata) -> JSON {
            var output = [ 
            "name": Serialization._StringSerializer.serialize(value.name),
            "path_lower": NullableSerializer(Serialization._StringSerializer).serialize(value.pathLower),
            "path_display": NullableSerializer(Serialization._StringSerializer).serialize(value.pathDisplay),
            "parent_shared_folder_id": NullableSerializer(Serialization._StringSerializer).serialize(value.parentSharedFolderId),
            ]
            switch value {
                case let file as Files.FileMetadata:
                    for (k, v) in Serialization.getFields(Files.FileMetadataSerializer().serialize(file)) {
                        output[k] = v
                    }
                    output[".tag"] = .str("file")
                case let folder as Files.FolderMetadata:
                    for (k, v) in Serialization.getFields(Files.FolderMetadataSerializer().serialize(folder)) {
                        output[k] = v
                    }
                    output[".tag"] = .str("folder")
                case let deleted as Files.DeletedMetadata:
                    for (k, v) in Serialization.getFields(Files.DeletedMetadataSerializer().serialize(deleted)) {
                        output[k] = v
                    }
                    output[".tag"] = .str("deleted")
                default: fatalError("Tried to serialize unexpected subtype")
            }
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> Metadata {
            switch json {
                case .dictionary(let dict):
                    let tag = Serialization.getTag(dict)
                    switch tag {
                        case "file":
                            return Files.FileMetadataSerializer().deserialize(json)
                        case "folder":
                            return Files.FolderMetadataSerializer().deserialize(json)
                        case "deleted":
                            return Files.DeletedMetadataSerializer().deserialize(json)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Indicates that there used to be a file or folder at this path, but it no longer exists.
    open class DeletedMetadata: Files.Metadata {
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DeletedMetadataSerializer().serialize(self)))"
        }
    }
    open class DeletedMetadataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DeletedMetadata) -> JSON {
            let output = [ 
            "name": Serialization._StringSerializer.serialize(value.name),
            "path_lower": NullableSerializer(Serialization._StringSerializer).serialize(value.pathLower),
            "path_display": NullableSerializer(Serialization._StringSerializer).serialize(value.pathDisplay),
            "parent_shared_folder_id": NullableSerializer(Serialization._StringSerializer).serialize(value.parentSharedFolderId),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DeletedMetadata {
            switch json {
                case .dictionary(let dict):
                    let name = Serialization._StringSerializer.deserialize(dict["name"] ?? .null)
                    let pathLower = NullableSerializer(Serialization._StringSerializer).deserialize(dict["path_lower"] ?? .null)
                    let pathDisplay = NullableSerializer(Serialization._StringSerializer).deserialize(dict["path_display"] ?? .null)
                    let parentSharedFolderId = NullableSerializer(Serialization._StringSerializer).deserialize(dict["parent_shared_folder_id"] ?? .null)
                    return DeletedMetadata(name: name, pathLower: pathLower, pathDisplay: pathDisplay, parentSharedFolderId: parentSharedFolderId)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Dimensions for a photo or video.
    open class Dimensions: CustomStringConvertible {
        /// Height of the photo/video.
        public let height: UInt64
        /// Width of the photo/video.
        public let width: UInt64
        public init(height: UInt64, width: UInt64) {
            comparableValidator()(height)
            self.height = height
            comparableValidator()(width)
            self.width = width
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DimensionsSerializer().serialize(self)))"
        }
    }
    open class DimensionsSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: Dimensions) -> JSON {
            let output = [ 
            "height": Serialization._UInt64Serializer.serialize(value.height),
            "width": Serialization._UInt64Serializer.serialize(value.width),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> Dimensions {
            switch json {
                case .dictionary(let dict):
                    let height = Serialization._UInt64Serializer.deserialize(dict["height"] ?? .null)
                    let width = Serialization._UInt64Serializer.deserialize(dict["width"] ?? .null)
                    return Dimensions(height: height, width: width)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The DownloadArg struct
    open class DownloadArg: CustomStringConvertible {
        /// The path of the file to download.
        public let path: String
        /// Please specify revision in path instead.
        public let rev: String?
        public init(path: String, rev: String? = nil) {
            stringValidator(pattern: "(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            nullableValidator(stringValidator(minLength: 9, pattern: "[0-9a-f]+"))(rev)
            self.rev = rev
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DownloadArgSerializer().serialize(self)))"
        }
    }
    open class DownloadArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DownloadArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "rev": NullableSerializer(Serialization._StringSerializer).serialize(value.rev),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DownloadArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let rev = NullableSerializer(Serialization._StringSerializer).deserialize(dict["rev"] ?? .null)
                    return DownloadArg(path: path, rev: rev)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The DownloadError union
    public enum DownloadError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// This file type cannot be downloaded directly; use export instead.
        case unsupportedFile
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DownloadErrorSerializer().serialize(self)))"
        }
    }
    open class DownloadErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DownloadError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .unsupportedFile:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_file")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> DownloadError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return DownloadError.path(v)
                        case "unsupported_file":
                            return DownloadError.unsupportedFile
                        case "other":
                            return DownloadError.other
                        default:
                            return DownloadError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The DownloadZipArg struct
    open class DownloadZipArg: CustomStringConvertible {
        /// The path of the folder to download.
        public let path: String
        public init(path: String) {
            stringValidator(pattern: "(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DownloadZipArgSerializer().serialize(self)))"
        }
    }
    open class DownloadZipArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DownloadZipArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DownloadZipArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    return DownloadZipArg(path: path)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The DownloadZipError union
    public enum DownloadZipError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// The folder or a file is too large to download.
        case tooLarge
        /// The folder has too many files to download.
        case tooManyFiles
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DownloadZipErrorSerializer().serialize(self)))"
        }
    }
    open class DownloadZipErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DownloadZipError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .tooLarge:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_large")
                    return .dictionary(d)
                case .tooManyFiles:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_files")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> DownloadZipError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return DownloadZipError.path(v)
                        case "too_large":
                            return DownloadZipError.tooLarge
                        case "too_many_files":
                            return DownloadZipError.tooManyFiles
                        case "other":
                            return DownloadZipError.other
                        default:
                            return DownloadZipError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The DownloadZipResult struct
    open class DownloadZipResult: CustomStringConvertible {
        /// (no description)
        public let metadata: Files.FolderMetadata
        public init(metadata: Files.FolderMetadata) {
            self.metadata = metadata
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(DownloadZipResultSerializer().serialize(self)))"
        }
    }
    open class DownloadZipResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: DownloadZipResult) -> JSON {
            let output = [ 
            "metadata": Files.FolderMetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> DownloadZipResult {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.FolderMetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return DownloadZipResult(metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ExportArg struct
    open class ExportArg: CustomStringConvertible {
        /// The path of the file to be exported.
        public let path: String
        public init(path: String) {
            stringValidator(pattern: "(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ExportArgSerializer().serialize(self)))"
        }
    }
    open class ExportArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ExportArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ExportArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    return ExportArg(path: path)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ExportError union
    public enum ExportError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// This file type cannot be exported. Use download instead.
        case nonExportable
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ExportErrorSerializer().serialize(self)))"
        }
    }
    open class ExportErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ExportError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .nonExportable:
                    var d = [String: JSON]()
                    d[".tag"] = .str("non_exportable")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ExportError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return ExportError.path(v)
                        case "non_exportable":
                            return ExportError.nonExportable
                        case "other":
                            return ExportError.other
                        default:
                            return ExportError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Export information for a file.
    open class ExportInfo: CustomStringConvertible {
        /// Format to which the file can be exported to.
        public let exportAs: String?
        public init(exportAs: String? = nil) {
            nullableValidator(stringValidator())(exportAs)
            self.exportAs = exportAs
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ExportInfoSerializer().serialize(self)))"
        }
    }
    open class ExportInfoSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ExportInfo) -> JSON {
            let output = [ 
            "export_as": NullableSerializer(Serialization._StringSerializer).serialize(value.exportAs),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ExportInfo {
            switch json {
                case .dictionary(let dict):
                    let exportAs = NullableSerializer(Serialization._StringSerializer).deserialize(dict["export_as"] ?? .null)
                    return ExportInfo(exportAs: exportAs)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ExportMetadata struct
    open class ExportMetadata: CustomStringConvertible {
        /// The last component of the path (including extension). This never contains a slash.
        public let name: String
        /// The file size in bytes.
        public let size: UInt64
        /// A hash based on the exported file content. This field can be used to verify data integrity. Similar to
        /// content hash. For more information see our Content hash
        /// https://www.dropbox.com/developers/reference/content-hash page.
        public let exportHash: String?
        public init(name: String, size: UInt64, exportHash: String? = nil) {
            stringValidator()(name)
            self.name = name
            comparableValidator()(size)
            self.size = size
            nullableValidator(stringValidator(minLength: 64, maxLength: 64))(exportHash)
            self.exportHash = exportHash
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ExportMetadataSerializer().serialize(self)))"
        }
    }
    open class ExportMetadataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ExportMetadata) -> JSON {
            let output = [ 
            "name": Serialization._StringSerializer.serialize(value.name),
            "size": Serialization._UInt64Serializer.serialize(value.size),
            "export_hash": NullableSerializer(Serialization._StringSerializer).serialize(value.exportHash),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ExportMetadata {
            switch json {
                case .dictionary(let dict):
                    let name = Serialization._StringSerializer.deserialize(dict["name"] ?? .null)
                    let size = Serialization._UInt64Serializer.deserialize(dict["size"] ?? .null)
                    let exportHash = NullableSerializer(Serialization._StringSerializer).deserialize(dict["export_hash"] ?? .null)
                    return ExportMetadata(name: name, size: size, exportHash: exportHash)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ExportResult struct
    open class ExportResult: CustomStringConvertible {
        /// Metadata for the exported version of the file.
        public let exportMetadata: Files.ExportMetadata
        /// Metadata for the original file.
        public let fileMetadata: Files.FileMetadata
        public init(exportMetadata: Files.ExportMetadata, fileMetadata: Files.FileMetadata) {
            self.exportMetadata = exportMetadata
            self.fileMetadata = fileMetadata
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ExportResultSerializer().serialize(self)))"
        }
    }
    open class ExportResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ExportResult) -> JSON {
            let output = [ 
            "export_metadata": Files.ExportMetadataSerializer().serialize(value.exportMetadata),
            "file_metadata": Files.FileMetadataSerializer().serialize(value.fileMetadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ExportResult {
            switch json {
                case .dictionary(let dict):
                    let exportMetadata = Files.ExportMetadataSerializer().deserialize(dict["export_metadata"] ?? .null)
                    let fileMetadata = Files.FileMetadataSerializer().deserialize(dict["file_metadata"] ?? .null)
                    return ExportResult(exportMetadata: exportMetadata, fileMetadata: fileMetadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The FileMetadata struct
    open class FileMetadata: Files.Metadata {
        /// A unique identifier for the file.
        public let id: String
        /// For files, this is the modification time set by the desktop client when the file was added to Dropbox. Since
        /// this time is not verified (the Dropbox server stores whatever the desktop client sends up), this should only
        /// be used for display purposes (such as sorting) and not, for example, to determine if a file has changed or
        /// not.
        public let clientModified: Date
        /// The last time the file was modified on Dropbox.
        public let serverModified: Date
        /// A unique identifier for the current revision of a file. This field is the same rev as elsewhere in the API
        /// and can be used to detect changes and avoid conflicts.
        public let rev: String
        /// The file size in bytes.
        public let size: UInt64
        /// Additional information if the file is a photo or video. This field will not be set on entries returned by
        /// listFolder, listFolderContinue, or getThumbnailBatch, starting December 2, 2019.
        public let mediaInfo: Files.MediaInfo?
        /// Set if this file is a symlink.
        public let symlinkInfo: Files.SymlinkInfo?
        /// Set if this file is contained in a shared folder.
        public let sharingInfo: Files.FileSharingInfo?
        /// If true, file can be downloaded directly; else the file must be exported.
        public let isDownloadable: Bool
        /// Information about format this file can be exported to. This filed must be set if isDownloadable is set to
        /// false.
        public let exportInfo: Files.ExportInfo?
        /// Additional information if the file has custom properties with the property template specified.
        public let propertyGroups: Array<FileProperties.PropertyGroup>?
        /// This flag will only be present if include_has_explicit_shared_members  is true in listFolder or getMetadata.
        /// If this  flag is present, it will be true if this file has any explicit shared  members. This is different
        /// from sharing_info in that this could be true  in the case where a file has explicit members but is not
        /// contained within  a shared folder.
        public let hasExplicitSharedMembers: Bool?
        /// A hash of the file content. This field can be used to verify data integrity. For more information see our
        /// Content hash https://www.dropbox.com/developers/reference/content-hash page.
        public let contentHash: String?
        public init(name: String, id: String, clientModified: Date, serverModified: Date, rev: String, size: UInt64, pathLower: String? = nil, pathDisplay: String? = nil, parentSharedFolderId: String? = nil, mediaInfo: Files.MediaInfo? = nil, symlinkInfo: Files.SymlinkInfo? = nil, sharingInfo: Files.FileSharingInfo? = nil, isDownloadable: Bool = true, exportInfo: Files.ExportInfo? = nil, propertyGroups: Array<FileProperties.PropertyGroup>? = nil, hasExplicitSharedMembers: Bool? = nil, contentHash: String? = nil) {
            stringValidator(minLength: 1)(id)
            self.id = id
            self.clientModified = clientModified
            self.serverModified = serverModified
            stringValidator(minLength: 9, pattern: "[0-9a-f]+")(rev)
            self.rev = rev
            comparableValidator()(size)
            self.size = size
            self.mediaInfo = mediaInfo
            self.symlinkInfo = symlinkInfo
            self.sharingInfo = sharingInfo
            self.isDownloadable = isDownloadable
            self.exportInfo = exportInfo
            self.propertyGroups = propertyGroups
            self.hasExplicitSharedMembers = hasExplicitSharedMembers
            nullableValidator(stringValidator(minLength: 64, maxLength: 64))(contentHash)
            self.contentHash = contentHash
            super.init(name: name, pathLower: pathLower, pathDisplay: pathDisplay, parentSharedFolderId: parentSharedFolderId)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(FileMetadataSerializer().serialize(self)))"
        }
    }
    open class FileMetadataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: FileMetadata) -> JSON {
            let output = [ 
            "name": Serialization._StringSerializer.serialize(value.name),
            "id": Serialization._StringSerializer.serialize(value.id),
            "client_modified": NSDateSerializer("%Y-%m-%dT%H:%M:%SZ").serialize(value.clientModified),
            "server_modified": NSDateSerializer("%Y-%m-%dT%H:%M:%SZ").serialize(value.serverModified),
            "rev": Serialization._StringSerializer.serialize(value.rev),
            "size": Serialization._UInt64Serializer.serialize(value.size),
            "path_lower": NullableSerializer(Serialization._StringSerializer).serialize(value.pathLower),
            "path_display": NullableSerializer(Serialization._StringSerializer).serialize(value.pathDisplay),
            "parent_shared_folder_id": NullableSerializer(Serialization._StringSerializer).serialize(value.parentSharedFolderId),
            "media_info": NullableSerializer(Files.MediaInfoSerializer()).serialize(value.mediaInfo),
            "symlink_info": NullableSerializer(Files.SymlinkInfoSerializer()).serialize(value.symlinkInfo),
            "sharing_info": NullableSerializer(Files.FileSharingInfoSerializer()).serialize(value.sharingInfo),
            "is_downloadable": Serialization._BoolSerializer.serialize(value.isDownloadable),
            "export_info": NullableSerializer(Files.ExportInfoSerializer()).serialize(value.exportInfo),
            "property_groups": NullableSerializer(ArraySerializer(FileProperties.PropertyGroupSerializer())).serialize(value.propertyGroups),
            "has_explicit_shared_members": NullableSerializer(Serialization._BoolSerializer).serialize(value.hasExplicitSharedMembers),
            "content_hash": NullableSerializer(Serialization._StringSerializer).serialize(value.contentHash),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> FileMetadata {
            switch json {
                case .dictionary(let dict):
                    let name = Serialization._StringSerializer.deserialize(dict["name"] ?? .null)
                    let id = Serialization._StringSerializer.deserialize(dict["id"] ?? .null)
                    let clientModified = NSDateSerializer("%Y-%m-%dT%H:%M:%SZ").deserialize(dict["client_modified"] ?? .null)
                    let serverModified = NSDateSerializer("%Y-%m-%dT%H:%M:%SZ").deserialize(dict["server_modified"] ?? .null)
                    let rev = Serialization._StringSerializer.deserialize(dict["rev"] ?? .null)
                    let size = Serialization._UInt64Serializer.deserialize(dict["size"] ?? .null)
                    let pathLower = NullableSerializer(Serialization._StringSerializer).deserialize(dict["path_lower"] ?? .null)
                    let pathDisplay = NullableSerializer(Serialization._StringSerializer).deserialize(dict["path_display"] ?? .null)
                    let parentSharedFolderId = NullableSerializer(Serialization._StringSerializer).deserialize(dict["parent_shared_folder_id"] ?? .null)
                    let mediaInfo = NullableSerializer(Files.MediaInfoSerializer()).deserialize(dict["media_info"] ?? .null)
                    let symlinkInfo = NullableSerializer(Files.SymlinkInfoSerializer()).deserialize(dict["symlink_info"] ?? .null)
                    let sharingInfo = NullableSerializer(Files.FileSharingInfoSerializer()).deserialize(dict["sharing_info"] ?? .null)
                    let isDownloadable = Serialization._BoolSerializer.deserialize(dict["is_downloadable"] ?? .number(1))
                    let exportInfo = NullableSerializer(Files.ExportInfoSerializer()).deserialize(dict["export_info"] ?? .null)
                    let propertyGroups = NullableSerializer(ArraySerializer(FileProperties.PropertyGroupSerializer())).deserialize(dict["property_groups"] ?? .null)
                    let hasExplicitSharedMembers = NullableSerializer(Serialization._BoolSerializer).deserialize(dict["has_explicit_shared_members"] ?? .null)
                    let contentHash = NullableSerializer(Serialization._StringSerializer).deserialize(dict["content_hash"] ?? .null)
                    return FileMetadata(name: name, id: id, clientModified: clientModified, serverModified: serverModified, rev: rev, size: size, pathLower: pathLower, pathDisplay: pathDisplay, parentSharedFolderId: parentSharedFolderId, mediaInfo: mediaInfo, symlinkInfo: symlinkInfo, sharingInfo: sharingInfo, isDownloadable: isDownloadable, exportInfo: exportInfo, propertyGroups: propertyGroups, hasExplicitSharedMembers: hasExplicitSharedMembers, contentHash: contentHash)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Sharing info for a file or folder.
    open class SharingInfo: CustomStringConvertible {
        /// True if the file or folder is inside a read-only shared folder.
        public let readOnly: Bool
        public init(readOnly: Bool) {
            self.readOnly = readOnly
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SharingInfoSerializer().serialize(self)))"
        }
    }
    open class SharingInfoSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SharingInfo) -> JSON {
            let output = [ 
            "read_only": Serialization._BoolSerializer.serialize(value.readOnly),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SharingInfo {
            switch json {
                case .dictionary(let dict):
                    let readOnly = Serialization._BoolSerializer.deserialize(dict["read_only"] ?? .null)
                    return SharingInfo(readOnly: readOnly)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Sharing info for a file which is contained by a shared folder.
    open class FileSharingInfo: Files.SharingInfo {
        /// ID of shared folder that holds this file.
        public let parentSharedFolderId: String
        /// The last user who modified the file. This field will be null if the user's account has been deleted.
        public let modifiedBy: String?
        public init(readOnly: Bool, parentSharedFolderId: String, modifiedBy: String? = nil) {
            stringValidator(pattern: "[-_0-9a-zA-Z:]+")(parentSharedFolderId)
            self.parentSharedFolderId = parentSharedFolderId
            nullableValidator(stringValidator(minLength: 40, maxLength: 40))(modifiedBy)
            self.modifiedBy = modifiedBy
            super.init(readOnly: readOnly)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(FileSharingInfoSerializer().serialize(self)))"
        }
    }
    open class FileSharingInfoSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: FileSharingInfo) -> JSON {
            let output = [ 
            "read_only": Serialization._BoolSerializer.serialize(value.readOnly),
            "parent_shared_folder_id": Serialization._StringSerializer.serialize(value.parentSharedFolderId),
            "modified_by": NullableSerializer(Serialization._StringSerializer).serialize(value.modifiedBy),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> FileSharingInfo {
            switch json {
                case .dictionary(let dict):
                    let readOnly = Serialization._BoolSerializer.deserialize(dict["read_only"] ?? .null)
                    let parentSharedFolderId = Serialization._StringSerializer.deserialize(dict["parent_shared_folder_id"] ?? .null)
                    let modifiedBy = NullableSerializer(Serialization._StringSerializer).deserialize(dict["modified_by"] ?? .null)
                    return FileSharingInfo(readOnly: readOnly, parentSharedFolderId: parentSharedFolderId, modifiedBy: modifiedBy)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The FolderMetadata struct
    open class FolderMetadata: Files.Metadata {
        /// A unique identifier for the folder.
        public let id: String
        /// Please use sharingInfo instead.
        public let sharedFolderId: String?
        /// Set if the folder is contained in a shared folder or is a shared folder mount point.
        public let sharingInfo: Files.FolderSharingInfo?
        /// Additional information if the file has custom properties with the property template specified. Note that
        /// only properties associated with user-owned templates, not team-owned templates, can be attached to folders.
        public let propertyGroups: Array<FileProperties.PropertyGroup>?
        public init(name: String, id: String, pathLower: String? = nil, pathDisplay: String? = nil, parentSharedFolderId: String? = nil, sharedFolderId: String? = nil, sharingInfo: Files.FolderSharingInfo? = nil, propertyGroups: Array<FileProperties.PropertyGroup>? = nil) {
            stringValidator(minLength: 1)(id)
            self.id = id
            nullableValidator(stringValidator(pattern: "[-_0-9a-zA-Z:]+"))(sharedFolderId)
            self.sharedFolderId = sharedFolderId
            self.sharingInfo = sharingInfo
            self.propertyGroups = propertyGroups
            super.init(name: name, pathLower: pathLower, pathDisplay: pathDisplay, parentSharedFolderId: parentSharedFolderId)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(FolderMetadataSerializer().serialize(self)))"
        }
    }
    open class FolderMetadataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: FolderMetadata) -> JSON {
            let output = [ 
            "name": Serialization._StringSerializer.serialize(value.name),
            "id": Serialization._StringSerializer.serialize(value.id),
            "path_lower": NullableSerializer(Serialization._StringSerializer).serialize(value.pathLower),
            "path_display": NullableSerializer(Serialization._StringSerializer).serialize(value.pathDisplay),
            "parent_shared_folder_id": NullableSerializer(Serialization._StringSerializer).serialize(value.parentSharedFolderId),
            "shared_folder_id": NullableSerializer(Serialization._StringSerializer).serialize(value.sharedFolderId),
            "sharing_info": NullableSerializer(Files.FolderSharingInfoSerializer()).serialize(value.sharingInfo),
            "property_groups": NullableSerializer(ArraySerializer(FileProperties.PropertyGroupSerializer())).serialize(value.propertyGroups),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> FolderMetadata {
            switch json {
                case .dictionary(let dict):
                    let name = Serialization._StringSerializer.deserialize(dict["name"] ?? .null)
                    let id = Serialization._StringSerializer.deserialize(dict["id"] ?? .null)
                    let pathLower = NullableSerializer(Serialization._StringSerializer).deserialize(dict["path_lower"] ?? .null)
                    let pathDisplay = NullableSerializer(Serialization._StringSerializer).deserialize(dict["path_display"] ?? .null)
                    let parentSharedFolderId = NullableSerializer(Serialization._StringSerializer).deserialize(dict["parent_shared_folder_id"] ?? .null)
                    let sharedFolderId = NullableSerializer(Serialization._StringSerializer).deserialize(dict["shared_folder_id"] ?? .null)
                    let sharingInfo = NullableSerializer(Files.FolderSharingInfoSerializer()).deserialize(dict["sharing_info"] ?? .null)
                    let propertyGroups = NullableSerializer(ArraySerializer(FileProperties.PropertyGroupSerializer())).deserialize(dict["property_groups"] ?? .null)
                    return FolderMetadata(name: name, id: id, pathLower: pathLower, pathDisplay: pathDisplay, parentSharedFolderId: parentSharedFolderId, sharedFolderId: sharedFolderId, sharingInfo: sharingInfo, propertyGroups: propertyGroups)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Sharing info for a folder which is contained in a shared folder or is a shared folder mount point.
    open class FolderSharingInfo: Files.SharingInfo {
        /// Set if the folder is contained by a shared folder.
        public let parentSharedFolderId: String?
        /// If this folder is a shared folder mount point, the ID of the shared folder mounted at this location.
        public let sharedFolderId: String?
        /// Specifies that the folder can only be traversed and the user can only see a limited subset of the contents
        /// of this folder because they don't have read access to this folder. They do, however, have access to some sub
        /// folder.
        public let traverseOnly: Bool
        /// Specifies that the folder cannot be accessed by the user.
        public let noAccess: Bool
        public init(readOnly: Bool, parentSharedFolderId: String? = nil, sharedFolderId: String? = nil, traverseOnly: Bool = false, noAccess: Bool = false) {
            nullableValidator(stringValidator(pattern: "[-_0-9a-zA-Z:]+"))(parentSharedFolderId)
            self.parentSharedFolderId = parentSharedFolderId
            nullableValidator(stringValidator(pattern: "[-_0-9a-zA-Z:]+"))(sharedFolderId)
            self.sharedFolderId = sharedFolderId
            self.traverseOnly = traverseOnly
            self.noAccess = noAccess
            super.init(readOnly: readOnly)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(FolderSharingInfoSerializer().serialize(self)))"
        }
    }
    open class FolderSharingInfoSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: FolderSharingInfo) -> JSON {
            let output = [ 
            "read_only": Serialization._BoolSerializer.serialize(value.readOnly),
            "parent_shared_folder_id": NullableSerializer(Serialization._StringSerializer).serialize(value.parentSharedFolderId),
            "shared_folder_id": NullableSerializer(Serialization._StringSerializer).serialize(value.sharedFolderId),
            "traverse_only": Serialization._BoolSerializer.serialize(value.traverseOnly),
            "no_access": Serialization._BoolSerializer.serialize(value.noAccess),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> FolderSharingInfo {
            switch json {
                case .dictionary(let dict):
                    let readOnly = Serialization._BoolSerializer.deserialize(dict["read_only"] ?? .null)
                    let parentSharedFolderId = NullableSerializer(Serialization._StringSerializer).deserialize(dict["parent_shared_folder_id"] ?? .null)
                    let sharedFolderId = NullableSerializer(Serialization._StringSerializer).deserialize(dict["shared_folder_id"] ?? .null)
                    let traverseOnly = Serialization._BoolSerializer.deserialize(dict["traverse_only"] ?? .number(0))
                    let noAccess = Serialization._BoolSerializer.deserialize(dict["no_access"] ?? .number(0))
                    return FolderSharingInfo(readOnly: readOnly, parentSharedFolderId: parentSharedFolderId, sharedFolderId: sharedFolderId, traverseOnly: traverseOnly, noAccess: noAccess)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetCopyReferenceArg struct
    open class GetCopyReferenceArg: CustomStringConvertible {
        /// The path to the file or folder you want to get a copy reference to.
        public let path: String
        public init(path: String) {
            stringValidator(pattern: "(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetCopyReferenceArgSerializer().serialize(self)))"
        }
    }
    open class GetCopyReferenceArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetCopyReferenceArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetCopyReferenceArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    return GetCopyReferenceArg(path: path)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetCopyReferenceError union
    public enum GetCopyReferenceError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetCopyReferenceErrorSerializer().serialize(self)))"
        }
    }
    open class GetCopyReferenceErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetCopyReferenceError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> GetCopyReferenceError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return GetCopyReferenceError.path(v)
                        case "other":
                            return GetCopyReferenceError.other
                        default:
                            return GetCopyReferenceError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The GetCopyReferenceResult struct
    open class GetCopyReferenceResult: CustomStringConvertible {
        /// Metadata of the file or folder.
        public let metadata: Files.Metadata
        /// A copy reference to the file or folder.
        public let copyReference: String
        /// The expiration date of the copy reference. This value is currently set to be far enough in the future so
        /// that expiration is effectively not an issue.
        public let expires: Date
        public init(metadata: Files.Metadata, copyReference: String, expires: Date) {
            self.metadata = metadata
            stringValidator()(copyReference)
            self.copyReference = copyReference
            self.expires = expires
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetCopyReferenceResultSerializer().serialize(self)))"
        }
    }
    open class GetCopyReferenceResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetCopyReferenceResult) -> JSON {
            let output = [ 
            "metadata": Files.MetadataSerializer().serialize(value.metadata),
            "copy_reference": Serialization._StringSerializer.serialize(value.copyReference),
            "expires": NSDateSerializer("%Y-%m-%dT%H:%M:%SZ").serialize(value.expires),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetCopyReferenceResult {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.MetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    let copyReference = Serialization._StringSerializer.deserialize(dict["copy_reference"] ?? .null)
                    let expires = NSDateSerializer("%Y-%m-%dT%H:%M:%SZ").deserialize(dict["expires"] ?? .null)
                    return GetCopyReferenceResult(metadata: metadata, copyReference: copyReference, expires: expires)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetTemporaryLinkArg struct
    open class GetTemporaryLinkArg: CustomStringConvertible {
        /// The path to the file you want a temporary link to.
        public let path: String
        public init(path: String) {
            stringValidator(pattern: "(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetTemporaryLinkArgSerializer().serialize(self)))"
        }
    }
    open class GetTemporaryLinkArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetTemporaryLinkArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetTemporaryLinkArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    return GetTemporaryLinkArg(path: path)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetTemporaryLinkError union
    public enum GetTemporaryLinkError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// The user's email address needs to be verified to use this functionality.
        case emailNotVerified
        /// Cannot get temporary link to this file type; use export instead.
        case unsupportedFile
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetTemporaryLinkErrorSerializer().serialize(self)))"
        }
    }
    open class GetTemporaryLinkErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetTemporaryLinkError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .emailNotVerified:
                    var d = [String: JSON]()
                    d[".tag"] = .str("email_not_verified")
                    return .dictionary(d)
                case .unsupportedFile:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_file")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> GetTemporaryLinkError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return GetTemporaryLinkError.path(v)
                        case "email_not_verified":
                            return GetTemporaryLinkError.emailNotVerified
                        case "unsupported_file":
                            return GetTemporaryLinkError.unsupportedFile
                        case "other":
                            return GetTemporaryLinkError.other
                        default:
                            return GetTemporaryLinkError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The GetTemporaryLinkResult struct
    open class GetTemporaryLinkResult: CustomStringConvertible {
        /// Metadata of the file.
        public let metadata: Files.FileMetadata
        /// The temporary link which can be used to stream content the file.
        public let link: String
        public init(metadata: Files.FileMetadata, link: String) {
            self.metadata = metadata
            stringValidator()(link)
            self.link = link
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetTemporaryLinkResultSerializer().serialize(self)))"
        }
    }
    open class GetTemporaryLinkResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetTemporaryLinkResult) -> JSON {
            let output = [ 
            "metadata": Files.FileMetadataSerializer().serialize(value.metadata),
            "link": Serialization._StringSerializer.serialize(value.link),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetTemporaryLinkResult {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.FileMetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    let link = Serialization._StringSerializer.deserialize(dict["link"] ?? .null)
                    return GetTemporaryLinkResult(metadata: metadata, link: link)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetTemporaryUploadLinkArg struct
    open class GetTemporaryUploadLinkArg: CustomStringConvertible {
        /// Contains the path and other optional modifiers for the future upload commit. Equivalent to the parameters
        /// provided to upload.
        public let commitInfo: Files.CommitInfo
        /// How long before this link expires, in seconds.  Attempting to start an upload with this link longer than
        /// this period  of time after link creation will result in an error.
        public let duration: Double
        public init(commitInfo: Files.CommitInfo, duration: Double = 14400.0) {
            self.commitInfo = commitInfo
            comparableValidator(minValue: 60.0, maxValue: 14400.0)(duration)
            self.duration = duration
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetTemporaryUploadLinkArgSerializer().serialize(self)))"
        }
    }
    open class GetTemporaryUploadLinkArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetTemporaryUploadLinkArg) -> JSON {
            let output = [ 
            "commit_info": Files.CommitInfoSerializer().serialize(value.commitInfo),
            "duration": Serialization._DoubleSerializer.serialize(value.duration),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetTemporaryUploadLinkArg {
            switch json {
                case .dictionary(let dict):
                    let commitInfo = Files.CommitInfoSerializer().deserialize(dict["commit_info"] ?? .null)
                    let duration = Serialization._DoubleSerializer.deserialize(dict["duration"] ?? .number(14400.0))
                    return GetTemporaryUploadLinkArg(commitInfo: commitInfo, duration: duration)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetTemporaryUploadLinkResult struct
    open class GetTemporaryUploadLinkResult: CustomStringConvertible {
        /// The temporary link which can be used to stream a file to a Dropbox location.
        public let link: String
        public init(link: String) {
            stringValidator()(link)
            self.link = link
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetTemporaryUploadLinkResultSerializer().serialize(self)))"
        }
    }
    open class GetTemporaryUploadLinkResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetTemporaryUploadLinkResult) -> JSON {
            let output = [ 
            "link": Serialization._StringSerializer.serialize(value.link),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetTemporaryUploadLinkResult {
            switch json {
                case .dictionary(let dict):
                    let link = Serialization._StringSerializer.deserialize(dict["link"] ?? .null)
                    return GetTemporaryUploadLinkResult(link: link)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Arguments for getThumbnailBatch.
    open class GetThumbnailBatchArg: CustomStringConvertible {
        /// List of files to get thumbnails.
        public let entries: Array<Files.ThumbnailArg>
        public init(entries: Array<Files.ThumbnailArg>) {
            self.entries = entries
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetThumbnailBatchArgSerializer().serialize(self)))"
        }
    }
    open class GetThumbnailBatchArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetThumbnailBatchArg) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.ThumbnailArgSerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetThumbnailBatchArg {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.ThumbnailArgSerializer()).deserialize(dict["entries"] ?? .null)
                    return GetThumbnailBatchArg(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetThumbnailBatchError union
    public enum GetThumbnailBatchError: CustomStringConvertible {
        /// The operation involves more than 25 files.
        case tooManyFiles
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetThumbnailBatchErrorSerializer().serialize(self)))"
        }
    }
    open class GetThumbnailBatchErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetThumbnailBatchError) -> JSON {
            switch value {
                case .tooManyFiles:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_files")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> GetThumbnailBatchError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "too_many_files":
                            return GetThumbnailBatchError.tooManyFiles
                        case "other":
                            return GetThumbnailBatchError.other
                        default:
                            return GetThumbnailBatchError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The GetThumbnailBatchResult struct
    open class GetThumbnailBatchResult: CustomStringConvertible {
        /// List of files and their thumbnails.
        public let entries: Array<Files.GetThumbnailBatchResultEntry>
        public init(entries: Array<Files.GetThumbnailBatchResultEntry>) {
            self.entries = entries
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetThumbnailBatchResultSerializer().serialize(self)))"
        }
    }
    open class GetThumbnailBatchResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetThumbnailBatchResult) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.GetThumbnailBatchResultEntrySerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetThumbnailBatchResult {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.GetThumbnailBatchResultEntrySerializer()).deserialize(dict["entries"] ?? .null)
                    return GetThumbnailBatchResult(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetThumbnailBatchResultData struct
    open class GetThumbnailBatchResultData: CustomStringConvertible {
        /// (no description)
        public let metadata: Files.FileMetadata
        /// A string containing the base64-encoded thumbnail data for this file.
        public let thumbnail: String
        public init(metadata: Files.FileMetadata, thumbnail: String) {
            self.metadata = metadata
            stringValidator()(thumbnail)
            self.thumbnail = thumbnail
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetThumbnailBatchResultDataSerializer().serialize(self)))"
        }
    }
    open class GetThumbnailBatchResultDataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetThumbnailBatchResultData) -> JSON {
            let output = [ 
            "metadata": Files.FileMetadataSerializer().serialize(value.metadata),
            "thumbnail": Serialization._StringSerializer.serialize(value.thumbnail),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GetThumbnailBatchResultData {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.FileMetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    let thumbnail = Serialization._StringSerializer.deserialize(dict["thumbnail"] ?? .null)
                    return GetThumbnailBatchResultData(metadata: metadata, thumbnail: thumbnail)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The GetThumbnailBatchResultEntry union
    public enum GetThumbnailBatchResultEntry: CustomStringConvertible {
        /// An unspecified error.
        case success(Files.GetThumbnailBatchResultData)
        /// The result for this file if it was an error.
        case failure(Files.ThumbnailError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GetThumbnailBatchResultEntrySerializer().serialize(self)))"
        }
    }
    open class GetThumbnailBatchResultEntrySerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GetThumbnailBatchResultEntry) -> JSON {
            switch value {
                case .success(let arg):
                    var d = Serialization.getFields(Files.GetThumbnailBatchResultDataSerializer().serialize(arg))
                    d[".tag"] = .str("success")
                    return .dictionary(d)
                case .failure(let arg):
                    var d = ["failure": Files.ThumbnailErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("failure")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> GetThumbnailBatchResultEntry {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "success":
                            let v = Files.GetThumbnailBatchResultDataSerializer().deserialize(json)
                            return GetThumbnailBatchResultEntry.success(v)
                        case "failure":
                            let v = Files.ThumbnailErrorSerializer().deserialize(d["failure"] ?? .null)
                            return GetThumbnailBatchResultEntry.failure(v)
                        case "other":
                            return GetThumbnailBatchResultEntry.other
                        default:
                            return GetThumbnailBatchResultEntry.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// GPS coordinates for a photo or video.
    open class GpsCoordinates: CustomStringConvertible {
        /// Latitude of the GPS coordinates.
        public let latitude: Double
        /// Longitude of the GPS coordinates.
        public let longitude: Double
        public init(latitude: Double, longitude: Double) {
            comparableValidator()(latitude)
            self.latitude = latitude
            comparableValidator()(longitude)
            self.longitude = longitude
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(GpsCoordinatesSerializer().serialize(self)))"
        }
    }
    open class GpsCoordinatesSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: GpsCoordinates) -> JSON {
            let output = [ 
            "latitude": Serialization._DoubleSerializer.serialize(value.latitude),
            "longitude": Serialization._DoubleSerializer.serialize(value.longitude),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> GpsCoordinates {
            switch json {
                case .dictionary(let dict):
                    let latitude = Serialization._DoubleSerializer.deserialize(dict["latitude"] ?? .null)
                    let longitude = Serialization._DoubleSerializer.deserialize(dict["longitude"] ?? .null)
                    return GpsCoordinates(latitude: latitude, longitude: longitude)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ListFolderArg struct
    open class ListFolderArg: CustomStringConvertible {
        /// A unique identifier for the file.
        public let path: String
        /// If true, the list folder operation will be applied recursively to all subfolders and the response will
        /// contain contents of all subfolders.
        public let recursive: Bool
        /// If true, mediaInfo in FileMetadata is set for photo and video. This parameter will no longer have an effect
        /// starting December 2, 2019.
        public let includeMediaInfo: Bool
        /// If true, the results will include entries for files and folders that used to exist but were deleted.
        public let includeDeleted: Bool
        /// If true, the results will include a flag for each file indicating whether or not  that file has any explicit
        /// members.
        public let includeHasExplicitSharedMembers: Bool
        /// If true, the results will include entries under mounted folders which includes app folder, shared folder and
        /// team folder.
        public let includeMountedFolders: Bool
        /// The maximum number of results to return per request. Note: This is an approximate number and there can be
        /// slightly more entries returned in some cases.
        public let limit: UInt32?
        /// A shared link to list the contents of. If the link is password-protected, the password must be provided. If
        /// this field is present, path in ListFolderArg will be relative to root of the shared link. Only non-recursive
        /// mode is supported for shared link.
        public let sharedLink: Files.SharedLink?
        /// If set to a valid list of template IDs, propertyGroups in FileMetadata is set if there exists property data
        /// associated with the file and each of the listed templates.
        public let includePropertyGroups: FileProperties.TemplateFilterBase?
        /// If true, include files that are not downloadable, i.e. Google Docs.
        public let includeNonDownloadableFiles: Bool
        public init(path: String, recursive: Bool = false, includeMediaInfo: Bool = false, includeDeleted: Bool = false, includeHasExplicitSharedMembers: Bool = false, includeMountedFolders: Bool = true, limit: UInt32? = nil, sharedLink: Files.SharedLink? = nil, includePropertyGroups: FileProperties.TemplateFilterBase? = nil, includeNonDownloadableFiles: Bool = true) {
            stringValidator(pattern: "(/(.|[\\r\\n])*)?|id:.*|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            self.recursive = recursive
            self.includeMediaInfo = includeMediaInfo
            self.includeDeleted = includeDeleted
            self.includeHasExplicitSharedMembers = includeHasExplicitSharedMembers
            self.includeMountedFolders = includeMountedFolders
            nullableValidator(comparableValidator(minValue: 1, maxValue: 2000))(limit)
            self.limit = limit
            self.sharedLink = sharedLink
            self.includePropertyGroups = includePropertyGroups
            self.includeNonDownloadableFiles = includeNonDownloadableFiles
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderArgSerializer().serialize(self)))"
        }
    }
    open class ListFolderArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "recursive": Serialization._BoolSerializer.serialize(value.recursive),
            "include_media_info": Serialization._BoolSerializer.serialize(value.includeMediaInfo),
            "include_deleted": Serialization._BoolSerializer.serialize(value.includeDeleted),
            "include_has_explicit_shared_members": Serialization._BoolSerializer.serialize(value.includeHasExplicitSharedMembers),
            "include_mounted_folders": Serialization._BoolSerializer.serialize(value.includeMountedFolders),
            "limit": NullableSerializer(Serialization._UInt32Serializer).serialize(value.limit),
            "shared_link": NullableSerializer(Files.SharedLinkSerializer()).serialize(value.sharedLink),
            "include_property_groups": NullableSerializer(FileProperties.TemplateFilterBaseSerializer()).serialize(value.includePropertyGroups),
            "include_non_downloadable_files": Serialization._BoolSerializer.serialize(value.includeNonDownloadableFiles),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ListFolderArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let recursive = Serialization._BoolSerializer.deserialize(dict["recursive"] ?? .number(0))
                    let includeMediaInfo = Serialization._BoolSerializer.deserialize(dict["include_media_info"] ?? .number(0))
                    let includeDeleted = Serialization._BoolSerializer.deserialize(dict["include_deleted"] ?? .number(0))
                    let includeHasExplicitSharedMembers = Serialization._BoolSerializer.deserialize(dict["include_has_explicit_shared_members"] ?? .number(0))
                    let includeMountedFolders = Serialization._BoolSerializer.deserialize(dict["include_mounted_folders"] ?? .number(1))
                    let limit = NullableSerializer(Serialization._UInt32Serializer).deserialize(dict["limit"] ?? .null)
                    let sharedLink = NullableSerializer(Files.SharedLinkSerializer()).deserialize(dict["shared_link"] ?? .null)
                    let includePropertyGroups = NullableSerializer(FileProperties.TemplateFilterBaseSerializer()).deserialize(dict["include_property_groups"] ?? .null)
                    let includeNonDownloadableFiles = Serialization._BoolSerializer.deserialize(dict["include_non_downloadable_files"] ?? .number(1))
                    return ListFolderArg(path: path, recursive: recursive, includeMediaInfo: includeMediaInfo, includeDeleted: includeDeleted, includeHasExplicitSharedMembers: includeHasExplicitSharedMembers, includeMountedFolders: includeMountedFolders, limit: limit, sharedLink: sharedLink, includePropertyGroups: includePropertyGroups, includeNonDownloadableFiles: includeNonDownloadableFiles)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ListFolderContinueArg struct
    open class ListFolderContinueArg: CustomStringConvertible {
        /// The cursor returned by your last call to listFolder or listFolderContinue.
        public let cursor: String
        public init(cursor: String) {
            stringValidator(minLength: 1)(cursor)
            self.cursor = cursor
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderContinueArgSerializer().serialize(self)))"
        }
    }
    open class ListFolderContinueArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderContinueArg) -> JSON {
            let output = [ 
            "cursor": Serialization._StringSerializer.serialize(value.cursor),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ListFolderContinueArg {
            switch json {
                case .dictionary(let dict):
                    let cursor = Serialization._StringSerializer.deserialize(dict["cursor"] ?? .null)
                    return ListFolderContinueArg(cursor: cursor)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ListFolderContinueError union
    public enum ListFolderContinueError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// Indicates that the cursor has been invalidated. Call listFolder to obtain a new cursor.
        case reset
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderContinueErrorSerializer().serialize(self)))"
        }
    }
    open class ListFolderContinueErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderContinueError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .reset:
                    var d = [String: JSON]()
                    d[".tag"] = .str("reset")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ListFolderContinueError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return ListFolderContinueError.path(v)
                        case "reset":
                            return ListFolderContinueError.reset
                        case "other":
                            return ListFolderContinueError.other
                        default:
                            return ListFolderContinueError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ListFolderError union
    public enum ListFolderError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderErrorSerializer().serialize(self)))"
        }
    }
    open class ListFolderErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ListFolderError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return ListFolderError.path(v)
                        case "other":
                            return ListFolderError.other
                        default:
                            return ListFolderError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ListFolderGetLatestCursorResult struct
    open class ListFolderGetLatestCursorResult: CustomStringConvertible {
        /// Pass the cursor into listFolderContinue to see what's changed in the folder since your previous query.
        public let cursor: String
        public init(cursor: String) {
            stringValidator(minLength: 1)(cursor)
            self.cursor = cursor
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderGetLatestCursorResultSerializer().serialize(self)))"
        }
    }
    open class ListFolderGetLatestCursorResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderGetLatestCursorResult) -> JSON {
            let output = [ 
            "cursor": Serialization._StringSerializer.serialize(value.cursor),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ListFolderGetLatestCursorResult {
            switch json {
                case .dictionary(let dict):
                    let cursor = Serialization._StringSerializer.deserialize(dict["cursor"] ?? .null)
                    return ListFolderGetLatestCursorResult(cursor: cursor)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ListFolderLongpollArg struct
    open class ListFolderLongpollArg: CustomStringConvertible {
        /// A cursor as returned by listFolder or listFolderContinue. Cursors retrieved by setting includeMediaInfo in
        /// ListFolderArg to true are not supported.
        public let cursor: String
        /// A timeout in seconds. The request will block for at most this length of time, plus up to 90 seconds of
        /// random jitter added to avoid the thundering herd problem. Care should be taken when using this parameter, as
        /// some network infrastructure does not support long timeouts.
        public let timeout: UInt64
        public init(cursor: String, timeout: UInt64 = 30) {
            stringValidator(minLength: 1)(cursor)
            self.cursor = cursor
            comparableValidator(minValue: 30, maxValue: 480)(timeout)
            self.timeout = timeout
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderLongpollArgSerializer().serialize(self)))"
        }
    }
    open class ListFolderLongpollArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderLongpollArg) -> JSON {
            let output = [ 
            "cursor": Serialization._StringSerializer.serialize(value.cursor),
            "timeout": Serialization._UInt64Serializer.serialize(value.timeout),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ListFolderLongpollArg {
            switch json {
                case .dictionary(let dict):
                    let cursor = Serialization._StringSerializer.deserialize(dict["cursor"] ?? .null)
                    let timeout = Serialization._UInt64Serializer.deserialize(dict["timeout"] ?? .number(30))
                    return ListFolderLongpollArg(cursor: cursor, timeout: timeout)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ListFolderLongpollError union
    public enum ListFolderLongpollError: CustomStringConvertible {
        /// Indicates that the cursor has been invalidated. Call listFolder to obtain a new cursor.
        case reset
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderLongpollErrorSerializer().serialize(self)))"
        }
    }
    open class ListFolderLongpollErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderLongpollError) -> JSON {
            switch value {
                case .reset:
                    var d = [String: JSON]()
                    d[".tag"] = .str("reset")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ListFolderLongpollError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "reset":
                            return ListFolderLongpollError.reset
                        case "other":
                            return ListFolderLongpollError.other
                        default:
                            return ListFolderLongpollError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ListFolderLongpollResult struct
    open class ListFolderLongpollResult: CustomStringConvertible {
        /// Indicates whether new changes are available. If true, call listFolderContinue to retrieve the changes.
        public let changes: Bool
        /// If present, backoff for at least this many seconds before calling listFolderLongpoll again.
        public let backoff: UInt64?
        public init(changes: Bool, backoff: UInt64? = nil) {
            self.changes = changes
            nullableValidator(comparableValidator())(backoff)
            self.backoff = backoff
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderLongpollResultSerializer().serialize(self)))"
        }
    }
    open class ListFolderLongpollResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderLongpollResult) -> JSON {
            let output = [ 
            "changes": Serialization._BoolSerializer.serialize(value.changes),
            "backoff": NullableSerializer(Serialization._UInt64Serializer).serialize(value.backoff),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ListFolderLongpollResult {
            switch json {
                case .dictionary(let dict):
                    let changes = Serialization._BoolSerializer.deserialize(dict["changes"] ?? .null)
                    let backoff = NullableSerializer(Serialization._UInt64Serializer).deserialize(dict["backoff"] ?? .null)
                    return ListFolderLongpollResult(changes: changes, backoff: backoff)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ListFolderResult struct
    open class ListFolderResult: CustomStringConvertible {
        /// The files and (direct) subfolders in the folder.
        public let entries: Array<Files.Metadata>
        /// Pass the cursor into listFolderContinue to see what's changed in the folder since your previous query.
        public let cursor: String
        /// If true, then there are more entries available. Pass the cursor to listFolderContinue to retrieve the rest.
        public let hasMore: Bool
        public init(entries: Array<Files.Metadata>, cursor: String, hasMore: Bool) {
            self.entries = entries
            stringValidator(minLength: 1)(cursor)
            self.cursor = cursor
            self.hasMore = hasMore
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListFolderResultSerializer().serialize(self)))"
        }
    }
    open class ListFolderResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListFolderResult) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.MetadataSerializer()).serialize(value.entries),
            "cursor": Serialization._StringSerializer.serialize(value.cursor),
            "has_more": Serialization._BoolSerializer.serialize(value.hasMore),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ListFolderResult {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.MetadataSerializer()).deserialize(dict["entries"] ?? .null)
                    let cursor = Serialization._StringSerializer.deserialize(dict["cursor"] ?? .null)
                    let hasMore = Serialization._BoolSerializer.deserialize(dict["has_more"] ?? .null)
                    return ListFolderResult(entries: entries, cursor: cursor, hasMore: hasMore)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ListRevisionsArg struct
    open class ListRevisionsArg: CustomStringConvertible {
        /// The path to the file you want to see the revisions of.
        public let path: String
        /// Determines the behavior of the API in listing the revisions for a given file path or id.
        public let mode: Files.ListRevisionsMode
        /// The maximum number of revision entries returned.
        public let limit: UInt64
        public init(path: String, mode: Files.ListRevisionsMode = .path, limit: UInt64 = 10) {
            stringValidator(pattern: "/(.|[\\r\\n])*|id:.*|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            self.mode = mode
            comparableValidator(minValue: 1, maxValue: 100)(limit)
            self.limit = limit
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListRevisionsArgSerializer().serialize(self)))"
        }
    }
    open class ListRevisionsArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListRevisionsArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "mode": Files.ListRevisionsModeSerializer().serialize(value.mode),
            "limit": Serialization._UInt64Serializer.serialize(value.limit),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ListRevisionsArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let mode = Files.ListRevisionsModeSerializer().deserialize(dict["mode"] ?? Files.ListRevisionsModeSerializer().serialize(.path))
                    let limit = Serialization._UInt64Serializer.deserialize(dict["limit"] ?? .number(10))
                    return ListRevisionsArg(path: path, mode: mode, limit: limit)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ListRevisionsError union
    public enum ListRevisionsError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListRevisionsErrorSerializer().serialize(self)))"
        }
    }
    open class ListRevisionsErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListRevisionsError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ListRevisionsError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return ListRevisionsError.path(v)
                        case "other":
                            return ListRevisionsError.other
                        default:
                            return ListRevisionsError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ListRevisionsMode union
    public enum ListRevisionsMode: CustomStringConvertible {
        /// Returns revisions with the same file path as identified by the latest file entry at the given file path or
        /// id.
        case path
        /// Returns revisions with the same file id as identified by the latest file entry at the given file path or id.
        case id
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListRevisionsModeSerializer().serialize(self)))"
        }
    }
    open class ListRevisionsModeSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListRevisionsMode) -> JSON {
            switch value {
                case .path:
                    var d = [String: JSON]()
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .id:
                    var d = [String: JSON]()
                    d[".tag"] = .str("id")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ListRevisionsMode {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            return ListRevisionsMode.path
                        case "id":
                            return ListRevisionsMode.id
                        case "other":
                            return ListRevisionsMode.other
                        default:
                            return ListRevisionsMode.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ListRevisionsResult struct
    open class ListRevisionsResult: CustomStringConvertible {
        /// If the file identified by the latest revision in the response is either deleted or moved.
        public let isDeleted: Bool
        /// The time of deletion if the file was deleted.
        public let serverDeleted: Date?
        /// The revisions for the file. Only revisions that are not deleted will show up here.
        public let entries: Array<Files.FileMetadata>
        public init(isDeleted: Bool, entries: Array<Files.FileMetadata>, serverDeleted: Date? = nil) {
            self.isDeleted = isDeleted
            self.serverDeleted = serverDeleted
            self.entries = entries
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ListRevisionsResultSerializer().serialize(self)))"
        }
    }
    open class ListRevisionsResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ListRevisionsResult) -> JSON {
            let output = [ 
            "is_deleted": Serialization._BoolSerializer.serialize(value.isDeleted),
            "entries": ArraySerializer(Files.FileMetadataSerializer()).serialize(value.entries),
            "server_deleted": NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).serialize(value.serverDeleted),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ListRevisionsResult {
            switch json {
                case .dictionary(let dict):
                    let isDeleted = Serialization._BoolSerializer.deserialize(dict["is_deleted"] ?? .null)
                    let entries = ArraySerializer(Files.FileMetadataSerializer()).deserialize(dict["entries"] ?? .null)
                    let serverDeleted = NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).deserialize(dict["server_deleted"] ?? .null)
                    return ListRevisionsResult(isDeleted: isDeleted, entries: entries, serverDeleted: serverDeleted)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The LookupError union
    public enum LookupError: CustomStringConvertible {
        /// The given path does not satisfy the required path format. Please refer to the Path formats documentation
        /// https://www.dropbox.com/developers/documentation/http/documentation#path-formats for more information.
        case malformedPath(String?)
        /// There is nothing at the given path.
        case notFound
        /// We were expecting a file, but the given path refers to something that isn't a file.
        case notFile
        /// We were expecting a folder, but the given path refers to something that isn't a folder.
        case notFolder
        /// The file cannot be transferred because the content is restricted.  For example, sometimes there are legal
        /// restrictions due to copyright claims.
        case restrictedContent
        /// This operation is not supported for this content type.
        case unsupportedContentType
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(LookupErrorSerializer().serialize(self)))"
        }
    }
    open class LookupErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: LookupError) -> JSON {
            switch value {
                case .malformedPath(let arg):
                    var d = ["malformed_path": NullableSerializer(Serialization._StringSerializer).serialize(arg)]
                    d[".tag"] = .str("malformed_path")
                    return .dictionary(d)
                case .notFound:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_found")
                    return .dictionary(d)
                case .notFile:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_file")
                    return .dictionary(d)
                case .notFolder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_folder")
                    return .dictionary(d)
                case .restrictedContent:
                    var d = [String: JSON]()
                    d[".tag"] = .str("restricted_content")
                    return .dictionary(d)
                case .unsupportedContentType:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_content_type")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> LookupError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "malformed_path":
                            let v = NullableSerializer(Serialization._StringSerializer).deserialize(d["malformed_path"] ?? .null)
                            return LookupError.malformedPath(v)
                        case "not_found":
                            return LookupError.notFound
                        case "not_file":
                            return LookupError.notFile
                        case "not_folder":
                            return LookupError.notFolder
                        case "restricted_content":
                            return LookupError.restrictedContent
                        case "unsupported_content_type":
                            return LookupError.unsupportedContentType
                        case "other":
                            return LookupError.other
                        default:
                            return LookupError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The MediaInfo union
    public enum MediaInfo: CustomStringConvertible {
        /// Indicate the photo/video is still under processing and metadata is not available yet.
        case pending
        /// The metadata for the photo/video.
        case metadata(Files.MediaMetadata)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(MediaInfoSerializer().serialize(self)))"
        }
    }
    open class MediaInfoSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: MediaInfo) -> JSON {
            switch value {
                case .pending:
                    var d = [String: JSON]()
                    d[".tag"] = .str("pending")
                    return .dictionary(d)
                case .metadata(let arg):
                    var d = ["metadata": Files.MediaMetadataSerializer().serialize(arg)]
                    d[".tag"] = .str("metadata")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> MediaInfo {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "pending":
                            return MediaInfo.pending
                        case "metadata":
                            let v = Files.MediaMetadataSerializer().deserialize(d["metadata"] ?? .null)
                            return MediaInfo.metadata(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Metadata for a photo or video.
    open class MediaMetadata: CustomStringConvertible {
        /// Dimension of the photo/video.
        public let dimensions: Files.Dimensions?
        /// The GPS coordinate of the photo/video.
        public let location: Files.GpsCoordinates?
        /// The timestamp when the photo/video is taken.
        public let timeTaken: Date?
        public init(dimensions: Files.Dimensions? = nil, location: Files.GpsCoordinates? = nil, timeTaken: Date? = nil) {
            self.dimensions = dimensions
            self.location = location
            self.timeTaken = timeTaken
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(MediaMetadataSerializer().serialize(self)))"
        }
    }
    open class MediaMetadataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: MediaMetadata) -> JSON {
            var output = [ 
            "dimensions": NullableSerializer(Files.DimensionsSerializer()).serialize(value.dimensions),
            "location": NullableSerializer(Files.GpsCoordinatesSerializer()).serialize(value.location),
            "time_taken": NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).serialize(value.timeTaken),
            ]
            switch value {
                case let photo as Files.PhotoMetadata:
                    for (k, v) in Serialization.getFields(Files.PhotoMetadataSerializer().serialize(photo)) {
                        output[k] = v
                    }
                    output[".tag"] = .str("photo")
                case let video as Files.VideoMetadata:
                    for (k, v) in Serialization.getFields(Files.VideoMetadataSerializer().serialize(video)) {
                        output[k] = v
                    }
                    output[".tag"] = .str("video")
                default: fatalError("Tried to serialize unexpected subtype")
            }
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> MediaMetadata {
            switch json {
                case .dictionary(let dict):
                    let tag = Serialization.getTag(dict)
                    switch tag {
                        case "photo":
                            return Files.PhotoMetadataSerializer().deserialize(json)
                        case "video":
                            return Files.VideoMetadataSerializer().deserialize(json)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RelocationBatchArgBase struct
    open class RelocationBatchArgBase: CustomStringConvertible {
        /// List of entries to be moved or copied. Each entry is RelocationPath.
        public let entries: Array<Files.RelocationPath>
        /// If there's a conflict with any file, have the Dropbox server try to autorename that file to avoid the
        /// conflict.
        public let autorename: Bool
        public init(entries: Array<Files.RelocationPath>, autorename: Bool = false) {
            self.entries = entries
            self.autorename = autorename
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchArgBaseSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchArgBaseSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchArgBase) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.RelocationPathSerializer()).serialize(value.entries),
            "autorename": Serialization._BoolSerializer.serialize(value.autorename),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RelocationBatchArgBase {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.RelocationPathSerializer()).deserialize(dict["entries"] ?? .null)
                    let autorename = Serialization._BoolSerializer.deserialize(dict["autorename"] ?? .number(0))
                    return RelocationBatchArgBase(entries: entries, autorename: autorename)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The MoveBatchArg struct
    open class MoveBatchArg: Files.RelocationBatchArgBase {
        /// Allow moves by owner even if it would result in an ownership transfer for the content being moved. This does
        /// not apply to copies.
        public let allowOwnershipTransfer: Bool
        public init(entries: Array<Files.RelocationPath>, autorename: Bool = false, allowOwnershipTransfer: Bool = false) {
            self.allowOwnershipTransfer = allowOwnershipTransfer
            super.init(entries: entries, autorename: autorename)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(MoveBatchArgSerializer().serialize(self)))"
        }
    }
    open class MoveBatchArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: MoveBatchArg) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.RelocationPathSerializer()).serialize(value.entries),
            "autorename": Serialization._BoolSerializer.serialize(value.autorename),
            "allow_ownership_transfer": Serialization._BoolSerializer.serialize(value.allowOwnershipTransfer),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> MoveBatchArg {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.RelocationPathSerializer()).deserialize(dict["entries"] ?? .null)
                    let autorename = Serialization._BoolSerializer.deserialize(dict["autorename"] ?? .number(0))
                    let allowOwnershipTransfer = Serialization._BoolSerializer.deserialize(dict["allow_ownership_transfer"] ?? .number(0))
                    return MoveBatchArg(entries: entries, autorename: autorename, allowOwnershipTransfer: allowOwnershipTransfer)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Metadata for a photo.
    open class PhotoMetadata: Files.MediaMetadata {
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(PhotoMetadataSerializer().serialize(self)))"
        }
    }
    open class PhotoMetadataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: PhotoMetadata) -> JSON {
            let output = [ 
            "dimensions": NullableSerializer(Files.DimensionsSerializer()).serialize(value.dimensions),
            "location": NullableSerializer(Files.GpsCoordinatesSerializer()).serialize(value.location),
            "time_taken": NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).serialize(value.timeTaken),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> PhotoMetadata {
            switch json {
                case .dictionary(let dict):
                    let dimensions = NullableSerializer(Files.DimensionsSerializer()).deserialize(dict["dimensions"] ?? .null)
                    let location = NullableSerializer(Files.GpsCoordinatesSerializer()).deserialize(dict["location"] ?? .null)
                    let timeTaken = NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).deserialize(dict["time_taken"] ?? .null)
                    return PhotoMetadata(dimensions: dimensions, location: location, timeTaken: timeTaken)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The PreviewArg struct
    open class PreviewArg: CustomStringConvertible {
        /// The path of the file to preview.
        public let path: String
        /// Please specify revision in path instead.
        public let rev: String?
        public init(path: String, rev: String? = nil) {
            stringValidator(pattern: "(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            nullableValidator(stringValidator(minLength: 9, pattern: "[0-9a-f]+"))(rev)
            self.rev = rev
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(PreviewArgSerializer().serialize(self)))"
        }
    }
    open class PreviewArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: PreviewArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "rev": NullableSerializer(Serialization._StringSerializer).serialize(value.rev),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> PreviewArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let rev = NullableSerializer(Serialization._StringSerializer).deserialize(dict["rev"] ?? .null)
                    return PreviewArg(path: path, rev: rev)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The PreviewError union
    public enum PreviewError: CustomStringConvertible {
        /// An error occurs when downloading metadata for the file.
        case path(Files.LookupError)
        /// This preview generation is still in progress and the file is not ready  for preview yet.
        case inProgress
        /// The file extension is not supported preview generation.
        case unsupportedExtension
        /// The file content is not supported for preview generation.
        case unsupportedContent
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(PreviewErrorSerializer().serialize(self)))"
        }
    }
    open class PreviewErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: PreviewError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .inProgress:
                    var d = [String: JSON]()
                    d[".tag"] = .str("in_progress")
                    return .dictionary(d)
                case .unsupportedExtension:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_extension")
                    return .dictionary(d)
                case .unsupportedContent:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_content")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> PreviewError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return PreviewError.path(v)
                        case "in_progress":
                            return PreviewError.inProgress
                        case "unsupported_extension":
                            return PreviewError.unsupportedExtension
                        case "unsupported_content":
                            return PreviewError.unsupportedContent
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The RelocationPath struct
    open class RelocationPath: CustomStringConvertible {
        /// Path in the user's Dropbox to be copied or moved.
        public let fromPath: String
        /// Path in the user's Dropbox that is the destination.
        public let toPath: String
        public init(fromPath: String, toPath: String) {
            stringValidator(pattern: "(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)|(id:.*)")(fromPath)
            self.fromPath = fromPath
            stringValidator(pattern: "(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)|(id:.*)")(toPath)
            self.toPath = toPath
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationPathSerializer().serialize(self)))"
        }
    }
    open class RelocationPathSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationPath) -> JSON {
            let output = [ 
            "from_path": Serialization._StringSerializer.serialize(value.fromPath),
            "to_path": Serialization._StringSerializer.serialize(value.toPath),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RelocationPath {
            switch json {
                case .dictionary(let dict):
                    let fromPath = Serialization._StringSerializer.deserialize(dict["from_path"] ?? .null)
                    let toPath = Serialization._StringSerializer.deserialize(dict["to_path"] ?? .null)
                    return RelocationPath(fromPath: fromPath, toPath: toPath)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RelocationArg struct
    open class RelocationArg: Files.RelocationPath {
        /// If true, copy will copy contents in shared folder, otherwise cantCopySharedFolder in RelocationError will be
        /// returned if fromPath contains shared folder. This field is always true for move.
        public let allowSharedFolder: Bool
        /// If there's a conflict, have the Dropbox server try to autorename the file to avoid the conflict.
        public let autorename: Bool
        /// Allow moves by owner even if it would result in an ownership transfer for the content being moved. This does
        /// not apply to copies.
        public let allowOwnershipTransfer: Bool
        public init(fromPath: String, toPath: String, allowSharedFolder: Bool = false, autorename: Bool = false, allowOwnershipTransfer: Bool = false) {
            self.allowSharedFolder = allowSharedFolder
            self.autorename = autorename
            self.allowOwnershipTransfer = allowOwnershipTransfer
            super.init(fromPath: fromPath, toPath: toPath)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationArgSerializer().serialize(self)))"
        }
    }
    open class RelocationArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationArg) -> JSON {
            let output = [ 
            "from_path": Serialization._StringSerializer.serialize(value.fromPath),
            "to_path": Serialization._StringSerializer.serialize(value.toPath),
            "allow_shared_folder": Serialization._BoolSerializer.serialize(value.allowSharedFolder),
            "autorename": Serialization._BoolSerializer.serialize(value.autorename),
            "allow_ownership_transfer": Serialization._BoolSerializer.serialize(value.allowOwnershipTransfer),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RelocationArg {
            switch json {
                case .dictionary(let dict):
                    let fromPath = Serialization._StringSerializer.deserialize(dict["from_path"] ?? .null)
                    let toPath = Serialization._StringSerializer.deserialize(dict["to_path"] ?? .null)
                    let allowSharedFolder = Serialization._BoolSerializer.deserialize(dict["allow_shared_folder"] ?? .number(0))
                    let autorename = Serialization._BoolSerializer.deserialize(dict["autorename"] ?? .number(0))
                    let allowOwnershipTransfer = Serialization._BoolSerializer.deserialize(dict["allow_ownership_transfer"] ?? .number(0))
                    return RelocationArg(fromPath: fromPath, toPath: toPath, allowSharedFolder: allowSharedFolder, autorename: autorename, allowOwnershipTransfer: allowOwnershipTransfer)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RelocationBatchArg struct
    open class RelocationBatchArg: Files.RelocationBatchArgBase {
        /// If true, copyBatch will copy contents in shared folder, otherwise cantCopySharedFolder in RelocationError
        /// will be returned if fromPath in RelocationPath contains shared folder. This field is always true for
        /// moveBatch.
        public let allowSharedFolder: Bool
        /// Allow moves by owner even if it would result in an ownership transfer for the content being moved. This does
        /// not apply to copies.
        public let allowOwnershipTransfer: Bool
        public init(entries: Array<Files.RelocationPath>, autorename: Bool = false, allowSharedFolder: Bool = false, allowOwnershipTransfer: Bool = false) {
            self.allowSharedFolder = allowSharedFolder
            self.allowOwnershipTransfer = allowOwnershipTransfer
            super.init(entries: entries, autorename: autorename)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchArgSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchArg) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.RelocationPathSerializer()).serialize(value.entries),
            "autorename": Serialization._BoolSerializer.serialize(value.autorename),
            "allow_shared_folder": Serialization._BoolSerializer.serialize(value.allowSharedFolder),
            "allow_ownership_transfer": Serialization._BoolSerializer.serialize(value.allowOwnershipTransfer),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RelocationBatchArg {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.RelocationPathSerializer()).deserialize(dict["entries"] ?? .null)
                    let autorename = Serialization._BoolSerializer.deserialize(dict["autorename"] ?? .number(0))
                    let allowSharedFolder = Serialization._BoolSerializer.deserialize(dict["allow_shared_folder"] ?? .number(0))
                    let allowOwnershipTransfer = Serialization._BoolSerializer.deserialize(dict["allow_ownership_transfer"] ?? .number(0))
                    return RelocationBatchArg(entries: entries, autorename: autorename, allowSharedFolder: allowSharedFolder, allowOwnershipTransfer: allowOwnershipTransfer)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RelocationError union
    public enum RelocationError: CustomStringConvertible {
        /// An unspecified error.
        case fromLookup(Files.LookupError)
        /// An unspecified error.
        case fromWrite(Files.WriteError)
        /// An unspecified error.
        case to(Files.WriteError)
        /// Shared folders can't be copied.
        case cantCopySharedFolder
        /// Your move operation would result in nested shared folders.  This is not allowed.
        case cantNestSharedFolder
        /// You cannot move a folder into itself.
        case cantMoveFolderIntoItself
        /// The operation would involve more than 10,000 files and folders.
        case tooManyFiles
        /// There are duplicated/nested paths among fromPath in RelocationArg and toPath in RelocationArg.
        case duplicatedOrNestedPaths
        /// Your move operation would result in an ownership transfer. You may reissue the request with the field
        /// allowOwnershipTransfer in RelocationArg to true.
        case cantTransferOwnership
        /// The current user does not have enough space to move or copy the files.
        case insufficientQuota
        /// Something went wrong with the job on Dropbox's end. You'll need to verify that the action you were taking
        /// succeeded, and if not, try again. This should happen very rarely.
        case internalError
        /// Can't move the shared folder to the given destination.
        case cantMoveSharedFolder
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationErrorSerializer().serialize(self)))"
        }
    }
    open class RelocationErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationError) -> JSON {
            switch value {
                case .fromLookup(let arg):
                    var d = ["from_lookup": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("from_lookup")
                    return .dictionary(d)
                case .fromWrite(let arg):
                    var d = ["from_write": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("from_write")
                    return .dictionary(d)
                case .to(let arg):
                    var d = ["to": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("to")
                    return .dictionary(d)
                case .cantCopySharedFolder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_copy_shared_folder")
                    return .dictionary(d)
                case .cantNestSharedFolder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_nest_shared_folder")
                    return .dictionary(d)
                case .cantMoveFolderIntoItself:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_move_folder_into_itself")
                    return .dictionary(d)
                case .tooManyFiles:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_files")
                    return .dictionary(d)
                case .duplicatedOrNestedPaths:
                    var d = [String: JSON]()
                    d[".tag"] = .str("duplicated_or_nested_paths")
                    return .dictionary(d)
                case .cantTransferOwnership:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_transfer_ownership")
                    return .dictionary(d)
                case .insufficientQuota:
                    var d = [String: JSON]()
                    d[".tag"] = .str("insufficient_quota")
                    return .dictionary(d)
                case .internalError:
                    var d = [String: JSON]()
                    d[".tag"] = .str("internal_error")
                    return .dictionary(d)
                case .cantMoveSharedFolder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_move_shared_folder")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RelocationError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "from_lookup":
                            let v = Files.LookupErrorSerializer().deserialize(d["from_lookup"] ?? .null)
                            return RelocationError.fromLookup(v)
                        case "from_write":
                            let v = Files.WriteErrorSerializer().deserialize(d["from_write"] ?? .null)
                            return RelocationError.fromWrite(v)
                        case "to":
                            let v = Files.WriteErrorSerializer().deserialize(d["to"] ?? .null)
                            return RelocationError.to(v)
                        case "cant_copy_shared_folder":
                            return RelocationError.cantCopySharedFolder
                        case "cant_nest_shared_folder":
                            return RelocationError.cantNestSharedFolder
                        case "cant_move_folder_into_itself":
                            return RelocationError.cantMoveFolderIntoItself
                        case "too_many_files":
                            return RelocationError.tooManyFiles
                        case "duplicated_or_nested_paths":
                            return RelocationError.duplicatedOrNestedPaths
                        case "cant_transfer_ownership":
                            return RelocationError.cantTransferOwnership
                        case "insufficient_quota":
                            return RelocationError.insufficientQuota
                        case "internal_error":
                            return RelocationError.internalError
                        case "cant_move_shared_folder":
                            return RelocationError.cantMoveSharedFolder
                        case "other":
                            return RelocationError.other
                        default:
                            return RelocationError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The RelocationBatchError union
    public enum RelocationBatchError: CustomStringConvertible {
        /// An unspecified error.
        case fromLookup(Files.LookupError)
        /// An unspecified error.
        case fromWrite(Files.WriteError)
        /// An unspecified error.
        case to(Files.WriteError)
        /// Shared folders can't be copied.
        case cantCopySharedFolder
        /// Your move operation would result in nested shared folders.  This is not allowed.
        case cantNestSharedFolder
        /// You cannot move a folder into itself.
        case cantMoveFolderIntoItself
        /// The operation would involve more than 10,000 files and folders.
        case tooManyFiles
        /// There are duplicated/nested paths among fromPath in RelocationArg and toPath in RelocationArg.
        case duplicatedOrNestedPaths
        /// Your move operation would result in an ownership transfer. You may reissue the request with the field
        /// allowOwnershipTransfer in RelocationArg to true.
        case cantTransferOwnership
        /// The current user does not have enough space to move or copy the files.
        case insufficientQuota
        /// Something went wrong with the job on Dropbox's end. You'll need to verify that the action you were taking
        /// succeeded, and if not, try again. This should happen very rarely.
        case internalError
        /// Can't move the shared folder to the given destination.
        case cantMoveSharedFolder
        /// An unspecified error.
        case other
        /// There are too many write operations in user's Dropbox. Please retry this request.
        case tooManyWriteOperations
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchErrorSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchError) -> JSON {
            switch value {
                case .fromLookup(let arg):
                    var d = ["from_lookup": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("from_lookup")
                    return .dictionary(d)
                case .fromWrite(let arg):
                    var d = ["from_write": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("from_write")
                    return .dictionary(d)
                case .to(let arg):
                    var d = ["to": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("to")
                    return .dictionary(d)
                case .cantCopySharedFolder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_copy_shared_folder")
                    return .dictionary(d)
                case .cantNestSharedFolder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_nest_shared_folder")
                    return .dictionary(d)
                case .cantMoveFolderIntoItself:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_move_folder_into_itself")
                    return .dictionary(d)
                case .tooManyFiles:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_files")
                    return .dictionary(d)
                case .duplicatedOrNestedPaths:
                    var d = [String: JSON]()
                    d[".tag"] = .str("duplicated_or_nested_paths")
                    return .dictionary(d)
                case .cantTransferOwnership:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_transfer_ownership")
                    return .dictionary(d)
                case .insufficientQuota:
                    var d = [String: JSON]()
                    d[".tag"] = .str("insufficient_quota")
                    return .dictionary(d)
                case .internalError:
                    var d = [String: JSON]()
                    d[".tag"] = .str("internal_error")
                    return .dictionary(d)
                case .cantMoveSharedFolder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("cant_move_shared_folder")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
                case .tooManyWriteOperations:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_write_operations")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RelocationBatchError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "from_lookup":
                            let v = Files.LookupErrorSerializer().deserialize(d["from_lookup"] ?? .null)
                            return RelocationBatchError.fromLookup(v)
                        case "from_write":
                            let v = Files.WriteErrorSerializer().deserialize(d["from_write"] ?? .null)
                            return RelocationBatchError.fromWrite(v)
                        case "to":
                            let v = Files.WriteErrorSerializer().deserialize(d["to"] ?? .null)
                            return RelocationBatchError.to(v)
                        case "cant_copy_shared_folder":
                            return RelocationBatchError.cantCopySharedFolder
                        case "cant_nest_shared_folder":
                            return RelocationBatchError.cantNestSharedFolder
                        case "cant_move_folder_into_itself":
                            return RelocationBatchError.cantMoveFolderIntoItself
                        case "too_many_files":
                            return RelocationBatchError.tooManyFiles
                        case "duplicated_or_nested_paths":
                            return RelocationBatchError.duplicatedOrNestedPaths
                        case "cant_transfer_ownership":
                            return RelocationBatchError.cantTransferOwnership
                        case "insufficient_quota":
                            return RelocationBatchError.insufficientQuota
                        case "internal_error":
                            return RelocationBatchError.internalError
                        case "cant_move_shared_folder":
                            return RelocationBatchError.cantMoveSharedFolder
                        case "other":
                            return RelocationBatchError.other
                        case "too_many_write_operations":
                            return RelocationBatchError.tooManyWriteOperations
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The RelocationBatchErrorEntry union
    public enum RelocationBatchErrorEntry: CustomStringConvertible {
        /// User errors that retry won't help.
        case relocationError(Files.RelocationError)
        /// Something went wrong with the job on Dropbox's end. You'll need to verify that the action you were taking
        /// succeeded, and if not, try again. This should happen very rarely.
        case internalError
        /// There are too many write operations in user's Dropbox. Please retry this request.
        case tooManyWriteOperations
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchErrorEntrySerializer().serialize(self)))"
        }
    }
    open class RelocationBatchErrorEntrySerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchErrorEntry) -> JSON {
            switch value {
                case .relocationError(let arg):
                    var d = ["relocation_error": Files.RelocationErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("relocation_error")
                    return .dictionary(d)
                case .internalError:
                    var d = [String: JSON]()
                    d[".tag"] = .str("internal_error")
                    return .dictionary(d)
                case .tooManyWriteOperations:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_write_operations")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RelocationBatchErrorEntry {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "relocation_error":
                            let v = Files.RelocationErrorSerializer().deserialize(d["relocation_error"] ?? .null)
                            return RelocationBatchErrorEntry.relocationError(v)
                        case "internal_error":
                            return RelocationBatchErrorEntry.internalError
                        case "too_many_write_operations":
                            return RelocationBatchErrorEntry.tooManyWriteOperations
                        case "other":
                            return RelocationBatchErrorEntry.other
                        default:
                            return RelocationBatchErrorEntry.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The RelocationBatchJobStatus union
    public enum RelocationBatchJobStatus: CustomStringConvertible {
        /// The asynchronous job is still in progress.
        case inProgress
        /// The copy or move batch job has finished.
        case complete(Files.RelocationBatchResult)
        /// The copy or move batch job has failed with exception.
        case failed(Files.RelocationBatchError)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchJobStatusSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchJobStatusSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchJobStatus) -> JSON {
            switch value {
                case .inProgress:
                    var d = [String: JSON]()
                    d[".tag"] = .str("in_progress")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.RelocationBatchResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
                case .failed(let arg):
                    var d = ["failed": Files.RelocationBatchErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("failed")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RelocationBatchJobStatus {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "in_progress":
                            return RelocationBatchJobStatus.inProgress
                        case "complete":
                            let v = Files.RelocationBatchResultSerializer().deserialize(json)
                            return RelocationBatchJobStatus.complete(v)
                        case "failed":
                            let v = Files.RelocationBatchErrorSerializer().deserialize(d["failed"] ?? .null)
                            return RelocationBatchJobStatus.failed(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Result returned by copyBatch or moveBatch that may either launch an asynchronous job or complete synchronously.
    public enum RelocationBatchLaunch: CustomStringConvertible {
        /// This response indicates that the processing is asynchronous. The string is an id that can be used to obtain
        /// the status of the asynchronous job.
        case asyncJobId(String)
        /// An unspecified error.
        case complete(Files.RelocationBatchResult)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchLaunchSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchLaunchSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchLaunch) -> JSON {
            switch value {
                case .asyncJobId(let arg):
                    var d = ["async_job_id": Serialization._StringSerializer.serialize(arg)]
                    d[".tag"] = .str("async_job_id")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.RelocationBatchResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RelocationBatchLaunch {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "async_job_id":
                            let v = Serialization._StringSerializer.deserialize(d["async_job_id"] ?? .null)
                            return RelocationBatchLaunch.asyncJobId(v)
                        case "complete":
                            let v = Files.RelocationBatchResultSerializer().deserialize(json)
                            return RelocationBatchLaunch.complete(v)
                        case "other":
                            return RelocationBatchLaunch.other
                        default:
                            return RelocationBatchLaunch.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The RelocationBatchResult struct
    open class RelocationBatchResult: Files.FileOpsResult {
        /// (no description)
        public let entries: Array<Files.RelocationBatchResultData>
        public init(entries: Array<Files.RelocationBatchResultData>) {
            self.entries = entries
            super.init()
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchResultSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchResult) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.RelocationBatchResultDataSerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RelocationBatchResult {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.RelocationBatchResultDataSerializer()).deserialize(dict["entries"] ?? .null)
                    return RelocationBatchResult(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RelocationBatchResultData struct
    open class RelocationBatchResultData: CustomStringConvertible {
        /// Metadata of the relocated object.
        public let metadata: Files.Metadata
        public init(metadata: Files.Metadata) {
            self.metadata = metadata
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchResultDataSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchResultDataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchResultData) -> JSON {
            let output = [ 
            "metadata": Files.MetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RelocationBatchResultData {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.MetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return RelocationBatchResultData(metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RelocationBatchResultEntry union
    public enum RelocationBatchResultEntry: CustomStringConvertible {
        /// An unspecified error.
        case success(Files.Metadata)
        /// An unspecified error.
        case failure(Files.RelocationBatchErrorEntry)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchResultEntrySerializer().serialize(self)))"
        }
    }
    open class RelocationBatchResultEntrySerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchResultEntry) -> JSON {
            switch value {
                case .success(let arg):
                    var d = ["success": Files.MetadataSerializer().serialize(arg)]
                    d[".tag"] = .str("success")
                    return .dictionary(d)
                case .failure(let arg):
                    var d = ["failure": Files.RelocationBatchErrorEntrySerializer().serialize(arg)]
                    d[".tag"] = .str("failure")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RelocationBatchResultEntry {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "success":
                            let v = Files.MetadataSerializer().deserialize(d["success"] ?? .null)
                            return RelocationBatchResultEntry.success(v)
                        case "failure":
                            let v = Files.RelocationBatchErrorEntrySerializer().deserialize(d["failure"] ?? .null)
                            return RelocationBatchResultEntry.failure(v)
                        case "other":
                            return RelocationBatchResultEntry.other
                        default:
                            return RelocationBatchResultEntry.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Result returned by copyBatchCheckV2 or moveBatchCheckV2 that may either be in progress or completed with result
    /// for each entry.
    public enum RelocationBatchV2JobStatus: CustomStringConvertible {
        /// The asynchronous job is still in progress.
        case inProgress
        /// The copy or move batch job has finished.
        case complete(Files.RelocationBatchV2Result)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchV2JobStatusSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchV2JobStatusSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchV2JobStatus) -> JSON {
            switch value {
                case .inProgress:
                    var d = [String: JSON]()
                    d[".tag"] = .str("in_progress")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.RelocationBatchV2ResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RelocationBatchV2JobStatus {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "in_progress":
                            return RelocationBatchV2JobStatus.inProgress
                        case "complete":
                            let v = Files.RelocationBatchV2ResultSerializer().deserialize(json)
                            return RelocationBatchV2JobStatus.complete(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Result returned by copyBatchV2 or moveBatchV2 that may either launch an asynchronous job or complete
    /// synchronously.
    public enum RelocationBatchV2Launch: CustomStringConvertible {
        /// This response indicates that the processing is asynchronous. The string is an id that can be used to obtain
        /// the status of the asynchronous job.
        case asyncJobId(String)
        /// An unspecified error.
        case complete(Files.RelocationBatchV2Result)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchV2LaunchSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchV2LaunchSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchV2Launch) -> JSON {
            switch value {
                case .asyncJobId(let arg):
                    var d = ["async_job_id": Serialization._StringSerializer.serialize(arg)]
                    d[".tag"] = .str("async_job_id")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.RelocationBatchV2ResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RelocationBatchV2Launch {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "async_job_id":
                            let v = Serialization._StringSerializer.deserialize(d["async_job_id"] ?? .null)
                            return RelocationBatchV2Launch.asyncJobId(v)
                        case "complete":
                            let v = Files.RelocationBatchV2ResultSerializer().deserialize(json)
                            return RelocationBatchV2Launch.complete(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The RelocationBatchV2Result struct
    open class RelocationBatchV2Result: Files.FileOpsResult {
        /// Each entry in CopyBatchArg.entries or entries in MoveBatchArg will appear at the same position inside
        /// entries in RelocationBatchV2Result.
        public let entries: Array<Files.RelocationBatchResultEntry>
        public init(entries: Array<Files.RelocationBatchResultEntry>) {
            self.entries = entries
            super.init()
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationBatchV2ResultSerializer().serialize(self)))"
        }
    }
    open class RelocationBatchV2ResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationBatchV2Result) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.RelocationBatchResultEntrySerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RelocationBatchV2Result {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.RelocationBatchResultEntrySerializer()).deserialize(dict["entries"] ?? .null)
                    return RelocationBatchV2Result(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RelocationResult struct
    open class RelocationResult: Files.FileOpsResult {
        /// Metadata of the relocated object.
        public let metadata: Files.Metadata
        public init(metadata: Files.Metadata) {
            self.metadata = metadata
            super.init()
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RelocationResultSerializer().serialize(self)))"
        }
    }
    open class RelocationResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RelocationResult) -> JSON {
            let output = [ 
            "metadata": Files.MetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RelocationResult {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.MetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return RelocationResult(metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RestoreArg struct
    open class RestoreArg: CustomStringConvertible {
        /// The path to save the restored file.
        public let path: String
        /// The revision to restore.
        public let rev: String
        public init(path: String, rev: String) {
            stringValidator(pattern: "(/(.|[\\r\\n])*)|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            stringValidator(minLength: 9, pattern: "[0-9a-f]+")(rev)
            self.rev = rev
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RestoreArgSerializer().serialize(self)))"
        }
    }
    open class RestoreArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RestoreArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "rev": Serialization._StringSerializer.serialize(value.rev),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> RestoreArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let rev = Serialization._StringSerializer.deserialize(dict["rev"] ?? .null)
                    return RestoreArg(path: path, rev: rev)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The RestoreError union
    public enum RestoreError: CustomStringConvertible {
        /// An error occurs when downloading metadata for the file.
        case pathLookup(Files.LookupError)
        /// An error occurs when trying to restore the file to that path.
        case pathWrite(Files.WriteError)
        /// The revision is invalid. It may not exist.
        case invalidRevision
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(RestoreErrorSerializer().serialize(self)))"
        }
    }
    open class RestoreErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: RestoreError) -> JSON {
            switch value {
                case .pathLookup(let arg):
                    var d = ["path_lookup": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path_lookup")
                    return .dictionary(d)
                case .pathWrite(let arg):
                    var d = ["path_write": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path_write")
                    return .dictionary(d)
                case .invalidRevision:
                    var d = [String: JSON]()
                    d[".tag"] = .str("invalid_revision")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> RestoreError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path_lookup":
                            let v = Files.LookupErrorSerializer().deserialize(d["path_lookup"] ?? .null)
                            return RestoreError.pathLookup(v)
                        case "path_write":
                            let v = Files.WriteErrorSerializer().deserialize(d["path_write"] ?? .null)
                            return RestoreError.pathWrite(v)
                        case "invalid_revision":
                            return RestoreError.invalidRevision
                        case "other":
                            return RestoreError.other
                        default:
                            return RestoreError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SaveCopyReferenceArg struct
    open class SaveCopyReferenceArg: CustomStringConvertible {
        /// A copy reference returned by copyReferenceGet.
        public let copyReference: String
        /// Path in the user's Dropbox that is the destination.
        public let path: String
        public init(copyReference: String, path: String) {
            stringValidator()(copyReference)
            self.copyReference = copyReference
            stringValidator(pattern: "/(.|[\\r\\n])*")(path)
            self.path = path
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SaveCopyReferenceArgSerializer().serialize(self)))"
        }
    }
    open class SaveCopyReferenceArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SaveCopyReferenceArg) -> JSON {
            let output = [ 
            "copy_reference": Serialization._StringSerializer.serialize(value.copyReference),
            "path": Serialization._StringSerializer.serialize(value.path),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SaveCopyReferenceArg {
            switch json {
                case .dictionary(let dict):
                    let copyReference = Serialization._StringSerializer.deserialize(dict["copy_reference"] ?? .null)
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    return SaveCopyReferenceArg(copyReference: copyReference, path: path)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The SaveCopyReferenceError union
    public enum SaveCopyReferenceError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.WriteError)
        /// The copy reference is invalid.
        case invalidCopyReference
        /// You don't have permission to save the given copy reference. Please make sure this app is same app which
        /// created the copy reference and the source user is still linked to the app.
        case noPermission
        /// The file referenced by the copy reference cannot be found.
        case notFound
        /// The operation would involve more than 10,000 files and folders.
        case tooManyFiles
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SaveCopyReferenceErrorSerializer().serialize(self)))"
        }
    }
    open class SaveCopyReferenceErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SaveCopyReferenceError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .invalidCopyReference:
                    var d = [String: JSON]()
                    d[".tag"] = .str("invalid_copy_reference")
                    return .dictionary(d)
                case .noPermission:
                    var d = [String: JSON]()
                    d[".tag"] = .str("no_permission")
                    return .dictionary(d)
                case .notFound:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_found")
                    return .dictionary(d)
                case .tooManyFiles:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_files")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SaveCopyReferenceError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.WriteErrorSerializer().deserialize(d["path"] ?? .null)
                            return SaveCopyReferenceError.path(v)
                        case "invalid_copy_reference":
                            return SaveCopyReferenceError.invalidCopyReference
                        case "no_permission":
                            return SaveCopyReferenceError.noPermission
                        case "not_found":
                            return SaveCopyReferenceError.notFound
                        case "too_many_files":
                            return SaveCopyReferenceError.tooManyFiles
                        case "other":
                            return SaveCopyReferenceError.other
                        default:
                            return SaveCopyReferenceError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SaveCopyReferenceResult struct
    open class SaveCopyReferenceResult: CustomStringConvertible {
        /// The metadata of the saved file or folder in the user's Dropbox.
        public let metadata: Files.Metadata
        public init(metadata: Files.Metadata) {
            self.metadata = metadata
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SaveCopyReferenceResultSerializer().serialize(self)))"
        }
    }
    open class SaveCopyReferenceResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SaveCopyReferenceResult) -> JSON {
            let output = [ 
            "metadata": Files.MetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SaveCopyReferenceResult {
            switch json {
                case .dictionary(let dict):
                    let metadata = Files.MetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return SaveCopyReferenceResult(metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The SaveUrlArg struct
    open class SaveUrlArg: CustomStringConvertible {
        /// The path in Dropbox where the URL will be saved to.
        public let path: String
        /// The URL to be saved.
        public let url: String
        public init(path: String, url: String) {
            stringValidator(pattern: "/(.|[\\r\\n])*")(path)
            self.path = path
            stringValidator()(url)
            self.url = url
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SaveUrlArgSerializer().serialize(self)))"
        }
    }
    open class SaveUrlArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SaveUrlArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "url": Serialization._StringSerializer.serialize(value.url),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SaveUrlArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let url = Serialization._StringSerializer.deserialize(dict["url"] ?? .null)
                    return SaveUrlArg(path: path, url: url)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The SaveUrlError union
    public enum SaveUrlError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.WriteError)
        /// Failed downloading the given URL. The url may be password-protected / the password provided was incorrect.
        case downloadFailed
        /// The given URL is invalid.
        case invalidUrl
        /// The file where the URL is saved to no longer exists.
        case notFound
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SaveUrlErrorSerializer().serialize(self)))"
        }
    }
    open class SaveUrlErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SaveUrlError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .downloadFailed:
                    var d = [String: JSON]()
                    d[".tag"] = .str("download_failed")
                    return .dictionary(d)
                case .invalidUrl:
                    var d = [String: JSON]()
                    d[".tag"] = .str("invalid_url")
                    return .dictionary(d)
                case .notFound:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_found")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SaveUrlError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.WriteErrorSerializer().deserialize(d["path"] ?? .null)
                            return SaveUrlError.path(v)
                        case "download_failed":
                            return SaveUrlError.downloadFailed
                        case "invalid_url":
                            return SaveUrlError.invalidUrl
                        case "not_found":
                            return SaveUrlError.notFound
                        case "other":
                            return SaveUrlError.other
                        default:
                            return SaveUrlError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SaveUrlJobStatus union
    public enum SaveUrlJobStatus: CustomStringConvertible {
        /// The asynchronous job is still in progress.
        case inProgress
        /// Metadata of the file where the URL is saved to.
        case complete(Files.FileMetadata)
        /// An unspecified error.
        case failed(Files.SaveUrlError)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SaveUrlJobStatusSerializer().serialize(self)))"
        }
    }
    open class SaveUrlJobStatusSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SaveUrlJobStatus) -> JSON {
            switch value {
                case .inProgress:
                    var d = [String: JSON]()
                    d[".tag"] = .str("in_progress")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.FileMetadataSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
                case .failed(let arg):
                    var d = ["failed": Files.SaveUrlErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("failed")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SaveUrlJobStatus {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "in_progress":
                            return SaveUrlJobStatus.inProgress
                        case "complete":
                            let v = Files.FileMetadataSerializer().deserialize(json)
                            return SaveUrlJobStatus.complete(v)
                        case "failed":
                            let v = Files.SaveUrlErrorSerializer().deserialize(d["failed"] ?? .null)
                            return SaveUrlJobStatus.failed(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SaveUrlResult union
    public enum SaveUrlResult: CustomStringConvertible {
        /// This response indicates that the processing is asynchronous. The string is an id that can be used to obtain
        /// the status of the asynchronous job.
        case asyncJobId(String)
        /// Metadata of the file where the URL is saved to.
        case complete(Files.FileMetadata)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SaveUrlResultSerializer().serialize(self)))"
        }
    }
    open class SaveUrlResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SaveUrlResult) -> JSON {
            switch value {
                case .asyncJobId(let arg):
                    var d = ["async_job_id": Serialization._StringSerializer.serialize(arg)]
                    d[".tag"] = .str("async_job_id")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.FileMetadataSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SaveUrlResult {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "async_job_id":
                            let v = Serialization._StringSerializer.deserialize(d["async_job_id"] ?? .null)
                            return SaveUrlResult.asyncJobId(v)
                        case "complete":
                            let v = Files.FileMetadataSerializer().deserialize(json)
                            return SaveUrlResult.complete(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SearchArg struct
    open class SearchArg: CustomStringConvertible {
        /// The path in the user's Dropbox to search. Should probably be a folder.
        public let path: String
        /// The string to search for. The search string is split on spaces into multiple tokens. For file name
        /// searching, the last token is used for prefix matching (i.e. "bat c" matches "bat cave" but not "batman
        /// car").
        public let query: String
        /// The starting index within the search results (used for paging).
        public let start: UInt64
        /// The maximum number of search results to return.
        public let maxResults: UInt64
        /// The search mode (filename, filename_and_content, or deleted_filename). Note that searching file content is
        /// only available for Dropbox Business accounts.
        public let mode: Files.SearchMode
        public init(path: String, query: String, start: UInt64 = 0, maxResults: UInt64 = 100, mode: Files.SearchMode = .filename) {
            stringValidator(pattern: "(/(.|[\\r\\n])*)?|id:.*|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            stringValidator()(query)
            self.query = query
            comparableValidator(maxValue: 9999)(start)
            self.start = start
            comparableValidator(minValue: 1, maxValue: 1000)(maxResults)
            self.maxResults = maxResults
            self.mode = mode
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SearchArgSerializer().serialize(self)))"
        }
    }
    open class SearchArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SearchArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "query": Serialization._StringSerializer.serialize(value.query),
            "start": Serialization._UInt64Serializer.serialize(value.start),
            "max_results": Serialization._UInt64Serializer.serialize(value.maxResults),
            "mode": Files.SearchModeSerializer().serialize(value.mode),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SearchArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let query = Serialization._StringSerializer.deserialize(dict["query"] ?? .null)
                    let start = Serialization._UInt64Serializer.deserialize(dict["start"] ?? .number(0))
                    let maxResults = Serialization._UInt64Serializer.deserialize(dict["max_results"] ?? .number(100))
                    let mode = Files.SearchModeSerializer().deserialize(dict["mode"] ?? Files.SearchModeSerializer().serialize(.filename))
                    return SearchArg(path: path, query: query, start: start, maxResults: maxResults, mode: mode)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The SearchError union
    public enum SearchError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SearchErrorSerializer().serialize(self)))"
        }
    }
    open class SearchErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SearchError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SearchError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return SearchError.path(v)
                        case "other":
                            return SearchError.other
                        default:
                            return SearchError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SearchMatch struct
    open class SearchMatch: CustomStringConvertible {
        /// The type of the match.
        public let matchType: Files.SearchMatchType
        /// The metadata for the matched file or folder.
        public let metadata: Files.Metadata
        public init(matchType: Files.SearchMatchType, metadata: Files.Metadata) {
            self.matchType = matchType
            self.metadata = metadata
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SearchMatchSerializer().serialize(self)))"
        }
    }
    open class SearchMatchSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SearchMatch) -> JSON {
            let output = [ 
            "match_type": Files.SearchMatchTypeSerializer().serialize(value.matchType),
            "metadata": Files.MetadataSerializer().serialize(value.metadata),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SearchMatch {
            switch json {
                case .dictionary(let dict):
                    let matchType = Files.SearchMatchTypeSerializer().deserialize(dict["match_type"] ?? .null)
                    let metadata = Files.MetadataSerializer().deserialize(dict["metadata"] ?? .null)
                    return SearchMatch(matchType: matchType, metadata: metadata)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Indicates what type of match was found for a given item.
    public enum SearchMatchType: CustomStringConvertible {
        /// This item was matched on its file or folder name.
        case filename
        /// This item was matched based on its file contents.
        case content
        /// This item was matched based on both its contents and its file name.
        case both
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SearchMatchTypeSerializer().serialize(self)))"
        }
    }
    open class SearchMatchTypeSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SearchMatchType) -> JSON {
            switch value {
                case .filename:
                    var d = [String: JSON]()
                    d[".tag"] = .str("filename")
                    return .dictionary(d)
                case .content:
                    var d = [String: JSON]()
                    d[".tag"] = .str("content")
                    return .dictionary(d)
                case .both:
                    var d = [String: JSON]()
                    d[".tag"] = .str("both")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SearchMatchType {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "filename":
                            return SearchMatchType.filename
                        case "content":
                            return SearchMatchType.content
                        case "both":
                            return SearchMatchType.both
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SearchMode union
    public enum SearchMode: CustomStringConvertible {
        /// Search file and folder names.
        case filename
        /// Search file and folder names as well as file contents.
        case filenameAndContent
        /// Search for deleted file and folder names.
        case deletedFilename
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SearchModeSerializer().serialize(self)))"
        }
    }
    open class SearchModeSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SearchMode) -> JSON {
            switch value {
                case .filename:
                    var d = [String: JSON]()
                    d[".tag"] = .str("filename")
                    return .dictionary(d)
                case .filenameAndContent:
                    var d = [String: JSON]()
                    d[".tag"] = .str("filename_and_content")
                    return .dictionary(d)
                case .deletedFilename:
                    var d = [String: JSON]()
                    d[".tag"] = .str("deleted_filename")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SearchMode {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "filename":
                            return SearchMode.filename
                        case "filename_and_content":
                            return SearchMode.filenameAndContent
                        case "deleted_filename":
                            return SearchMode.deletedFilename
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SearchResult struct
    open class SearchResult: CustomStringConvertible {
        /// A list (possibly empty) of matches for the query.
        public let matches: Array<Files.SearchMatch>
        /// Used for paging. If true, indicates there is another page of results available that can be fetched by
        /// calling search again.
        public let more: Bool
        /// Used for paging. Value to set the start argument to when calling search to fetch the next page of results.
        public let start: UInt64
        public init(matches: Array<Files.SearchMatch>, more: Bool, start: UInt64) {
            self.matches = matches
            self.more = more
            comparableValidator()(start)
            self.start = start
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SearchResultSerializer().serialize(self)))"
        }
    }
    open class SearchResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SearchResult) -> JSON {
            let output = [ 
            "matches": ArraySerializer(Files.SearchMatchSerializer()).serialize(value.matches),
            "more": Serialization._BoolSerializer.serialize(value.more),
            "start": Serialization._UInt64Serializer.serialize(value.start),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SearchResult {
            switch json {
                case .dictionary(let dict):
                    let matches = ArraySerializer(Files.SearchMatchSerializer()).deserialize(dict["matches"] ?? .null)
                    let more = Serialization._BoolSerializer.deserialize(dict["more"] ?? .null)
                    let start = Serialization._UInt64Serializer.deserialize(dict["start"] ?? .null)
                    return SearchResult(matches: matches, more: more, start: start)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The SharedLink struct
    open class SharedLink: CustomStringConvertible {
        /// Shared link url.
        public let url: String
        /// Password for the shared link.
        public let password: String?
        public init(url: String, password: String? = nil) {
            stringValidator()(url)
            self.url = url
            nullableValidator(stringValidator())(password)
            self.password = password
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SharedLinkSerializer().serialize(self)))"
        }
    }
    open class SharedLinkSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SharedLink) -> JSON {
            let output = [ 
            "url": Serialization._StringSerializer.serialize(value.url),
            "password": NullableSerializer(Serialization._StringSerializer).serialize(value.password),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SharedLink {
            switch json {
                case .dictionary(let dict):
                    let url = Serialization._StringSerializer.deserialize(dict["url"] ?? .null)
                    let password = NullableSerializer(Serialization._StringSerializer).deserialize(dict["password"] ?? .null)
                    return SharedLink(url: url, password: password)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The SymlinkInfo struct
    open class SymlinkInfo: CustomStringConvertible {
        /// The target this symlink points to.
        public let target: String
        public init(target: String) {
            stringValidator()(target)
            self.target = target
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SymlinkInfoSerializer().serialize(self)))"
        }
    }
    open class SymlinkInfoSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SymlinkInfo) -> JSON {
            let output = [ 
            "target": Serialization._StringSerializer.serialize(value.target),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> SymlinkInfo {
            switch json {
                case .dictionary(let dict):
                    let target = Serialization._StringSerializer.deserialize(dict["target"] ?? .null)
                    return SymlinkInfo(target: target)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The SyncSetting union
    public enum SyncSetting: CustomStringConvertible {
        /// On first sync to members' computers, the specified folder will follow its parent folder's setting or
        /// otherwise follow default sync behavior.
        case default_
        /// On first sync to members' computers, the specified folder will be set to not sync with selective sync.
        case notSynced
        /// The specified folder's not_synced setting is inactive due to its location or other configuration changes. It
        /// will follow its parent folder's setting.
        case notSyncedInactive
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SyncSettingSerializer().serialize(self)))"
        }
    }
    open class SyncSettingSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SyncSetting) -> JSON {
            switch value {
                case .default_:
                    var d = [String: JSON]()
                    d[".tag"] = .str("default")
                    return .dictionary(d)
                case .notSynced:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_synced")
                    return .dictionary(d)
                case .notSyncedInactive:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_synced_inactive")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SyncSetting {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "default":
                            return SyncSetting.default_
                        case "not_synced":
                            return SyncSetting.notSynced
                        case "not_synced_inactive":
                            return SyncSetting.notSyncedInactive
                        case "other":
                            return SyncSetting.other
                        default:
                            return SyncSetting.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SyncSettingArg union
    public enum SyncSettingArg: CustomStringConvertible {
        /// On first sync to members' computers, the specified folder will follow its parent folder's setting or
        /// otherwise follow default sync behavior.
        case default_
        /// On first sync to members' computers, the specified folder will be set to not sync with selective sync.
        case notSynced
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SyncSettingArgSerializer().serialize(self)))"
        }
    }
    open class SyncSettingArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SyncSettingArg) -> JSON {
            switch value {
                case .default_:
                    var d = [String: JSON]()
                    d[".tag"] = .str("default")
                    return .dictionary(d)
                case .notSynced:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_synced")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SyncSettingArg {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "default":
                            return SyncSettingArg.default_
                        case "not_synced":
                            return SyncSettingArg.notSynced
                        case "other":
                            return SyncSettingArg.other
                        default:
                            return SyncSettingArg.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The SyncSettingsError union
    public enum SyncSettingsError: CustomStringConvertible {
        /// An unspecified error.
        case path(Files.LookupError)
        /// Setting this combination of sync settings simultaneously is not supported.
        case unsupportedCombination
        /// The specified configuration is not supported.
        case unsupportedConfiguration
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(SyncSettingsErrorSerializer().serialize(self)))"
        }
    }
    open class SyncSettingsErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: SyncSettingsError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .unsupportedCombination:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_combination")
                    return .dictionary(d)
                case .unsupportedConfiguration:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_configuration")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> SyncSettingsError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return SyncSettingsError.path(v)
                        case "unsupported_combination":
                            return SyncSettingsError.unsupportedCombination
                        case "unsupported_configuration":
                            return SyncSettingsError.unsupportedConfiguration
                        case "other":
                            return SyncSettingsError.other
                        default:
                            return SyncSettingsError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ThumbnailArg struct
    open class ThumbnailArg: CustomStringConvertible {
        /// The path to the image file you want to thumbnail.
        public let path: String
        /// The format for the thumbnail image, jpeg (default) or png. For  images that are photos, jpeg should be
        /// preferred, while png is  better for screenshots and digital arts.
        public let format: Files.ThumbnailFormat
        /// The size for the thumbnail image.
        public let size: Files.ThumbnailSize
        /// How to resize and crop the image to achieve the desired size.
        public let mode: Files.ThumbnailMode
        public init(path: String, format: Files.ThumbnailFormat = .jpeg, size: Files.ThumbnailSize = .w64h64, mode: Files.ThumbnailMode = .strict) {
            stringValidator(pattern: "(/(.|[\\r\\n])*|id:.*)|(rev:[0-9a-f]{9,})|(ns:[0-9]+(/.*)?)")(path)
            self.path = path
            self.format = format
            self.size = size
            self.mode = mode
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ThumbnailArgSerializer().serialize(self)))"
        }
    }
    open class ThumbnailArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ThumbnailArg) -> JSON {
            let output = [ 
            "path": Serialization._StringSerializer.serialize(value.path),
            "format": Files.ThumbnailFormatSerializer().serialize(value.format),
            "size": Files.ThumbnailSizeSerializer().serialize(value.size),
            "mode": Files.ThumbnailModeSerializer().serialize(value.mode),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> ThumbnailArg {
            switch json {
                case .dictionary(let dict):
                    let path = Serialization._StringSerializer.deserialize(dict["path"] ?? .null)
                    let format = Files.ThumbnailFormatSerializer().deserialize(dict["format"] ?? Files.ThumbnailFormatSerializer().serialize(.jpeg))
                    let size = Files.ThumbnailSizeSerializer().deserialize(dict["size"] ?? Files.ThumbnailSizeSerializer().serialize(.w64h64))
                    let mode = Files.ThumbnailModeSerializer().deserialize(dict["mode"] ?? Files.ThumbnailModeSerializer().serialize(.strict))
                    return ThumbnailArg(path: path, format: format, size: size, mode: mode)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The ThumbnailError union
    public enum ThumbnailError: CustomStringConvertible {
        /// An error occurs when downloading metadata for the image.
        case path(Files.LookupError)
        /// The file extension doesn't allow conversion to a thumbnail.
        case unsupportedExtension
        /// The image cannot be converted to a thumbnail.
        case unsupportedImage
        /// An error occurs during thumbnail conversion.
        case conversionError
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ThumbnailErrorSerializer().serialize(self)))"
        }
    }
    open class ThumbnailErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ThumbnailError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = ["path": Files.LookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .unsupportedExtension:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_extension")
                    return .dictionary(d)
                case .unsupportedImage:
                    var d = [String: JSON]()
                    d[".tag"] = .str("unsupported_image")
                    return .dictionary(d)
                case .conversionError:
                    var d = [String: JSON]()
                    d[".tag"] = .str("conversion_error")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ThumbnailError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.LookupErrorSerializer().deserialize(d["path"] ?? .null)
                            return ThumbnailError.path(v)
                        case "unsupported_extension":
                            return ThumbnailError.unsupportedExtension
                        case "unsupported_image":
                            return ThumbnailError.unsupportedImage
                        case "conversion_error":
                            return ThumbnailError.conversionError
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ThumbnailFormat union
    public enum ThumbnailFormat: CustomStringConvertible {
        /// An unspecified error.
        case jpeg
        /// An unspecified error.
        case png
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ThumbnailFormatSerializer().serialize(self)))"
        }
    }
    open class ThumbnailFormatSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ThumbnailFormat) -> JSON {
            switch value {
                case .jpeg:
                    var d = [String: JSON]()
                    d[".tag"] = .str("jpeg")
                    return .dictionary(d)
                case .png:
                    var d = [String: JSON]()
                    d[".tag"] = .str("png")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ThumbnailFormat {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "jpeg":
                            return ThumbnailFormat.jpeg
                        case "png":
                            return ThumbnailFormat.png
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ThumbnailMode union
    public enum ThumbnailMode: CustomStringConvertible {
        /// Scale down the image to fit within the given size.
        case strict
        /// Scale down the image to fit within the given size or its transpose.
        case bestfit
        /// Scale down the image to completely cover the given size or its transpose.
        case fitoneBestfit
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ThumbnailModeSerializer().serialize(self)))"
        }
    }
    open class ThumbnailModeSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ThumbnailMode) -> JSON {
            switch value {
                case .strict:
                    var d = [String: JSON]()
                    d[".tag"] = .str("strict")
                    return .dictionary(d)
                case .bestfit:
                    var d = [String: JSON]()
                    d[".tag"] = .str("bestfit")
                    return .dictionary(d)
                case .fitoneBestfit:
                    var d = [String: JSON]()
                    d[".tag"] = .str("fitone_bestfit")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ThumbnailMode {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "strict":
                            return ThumbnailMode.strict
                        case "bestfit":
                            return ThumbnailMode.bestfit
                        case "fitone_bestfit":
                            return ThumbnailMode.fitoneBestfit
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The ThumbnailSize union
    public enum ThumbnailSize: CustomStringConvertible {
        /// 32 by 32 px.
        case w32h32
        /// 64 by 64 px.
        case w64h64
        /// 128 by 128 px.
        case w128h128
        /// 256 by 256 px.
        case w256h256
        /// 480 by 320 px.
        case w480h320
        /// 640 by 480 px.
        case w640h480
        /// 960 by 640 px.
        case w960h640
        /// 1024 by 768 px.
        case w1024h768
        /// 2048 by 1536 px.
        case w2048h1536
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(ThumbnailSizeSerializer().serialize(self)))"
        }
    }
    open class ThumbnailSizeSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: ThumbnailSize) -> JSON {
            switch value {
                case .w32h32:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w32h32")
                    return .dictionary(d)
                case .w64h64:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w64h64")
                    return .dictionary(d)
                case .w128h128:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w128h128")
                    return .dictionary(d)
                case .w256h256:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w256h256")
                    return .dictionary(d)
                case .w480h320:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w480h320")
                    return .dictionary(d)
                case .w640h480:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w640h480")
                    return .dictionary(d)
                case .w960h640:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w960h640")
                    return .dictionary(d)
                case .w1024h768:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w1024h768")
                    return .dictionary(d)
                case .w2048h1536:
                    var d = [String: JSON]()
                    d[".tag"] = .str("w2048h1536")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> ThumbnailSize {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "w32h32":
                            return ThumbnailSize.w32h32
                        case "w64h64":
                            return ThumbnailSize.w64h64
                        case "w128h128":
                            return ThumbnailSize.w128h128
                        case "w256h256":
                            return ThumbnailSize.w256h256
                        case "w480h320":
                            return ThumbnailSize.w480h320
                        case "w640h480":
                            return ThumbnailSize.w640h480
                        case "w960h640":
                            return ThumbnailSize.w960h640
                        case "w1024h768":
                            return ThumbnailSize.w1024h768
                        case "w2048h1536":
                            return ThumbnailSize.w2048h1536
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The UploadError union
    public enum UploadError: CustomStringConvertible {
        /// Unable to save the uploaded contents to a file.
        case path(Files.UploadWriteFailed)
        /// The supplied property group is invalid. The file has uploaded without property groups.
        case propertiesError(FileProperties.InvalidPropertyGroupError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadErrorSerializer().serialize(self)))"
        }
    }
    open class UploadErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadError) -> JSON {
            switch value {
                case .path(let arg):
                    var d = Serialization.getFields(Files.UploadWriteFailedSerializer().serialize(arg))
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .propertiesError(let arg):
                    var d = ["properties_error": FileProperties.InvalidPropertyGroupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("properties_error")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> UploadError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.UploadWriteFailedSerializer().deserialize(json)
                            return UploadError.path(v)
                        case "properties_error":
                            let v = FileProperties.InvalidPropertyGroupErrorSerializer().deserialize(d["properties_error"] ?? .null)
                            return UploadError.propertiesError(v)
                        case "other":
                            return UploadError.other
                        default:
                            return UploadError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The UploadErrorWithProperties union
    public enum UploadErrorWithProperties: CustomStringConvertible {
        /// Unable to save the uploaded contents to a file.
        case path(Files.UploadWriteFailed)
        /// The supplied property group is invalid. The file has uploaded without property groups.
        case propertiesError(FileProperties.InvalidPropertyGroupError)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadErrorWithPropertiesSerializer().serialize(self)))"
        }
    }
    open class UploadErrorWithPropertiesSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadErrorWithProperties) -> JSON {
            switch value {
                case .path(let arg):
                    var d = Serialization.getFields(Files.UploadWriteFailedSerializer().serialize(arg))
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .propertiesError(let arg):
                    var d = ["properties_error": FileProperties.InvalidPropertyGroupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("properties_error")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> UploadErrorWithProperties {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "path":
                            let v = Files.UploadWriteFailedSerializer().deserialize(json)
                            return UploadErrorWithProperties.path(v)
                        case "properties_error":
                            let v = FileProperties.InvalidPropertyGroupErrorSerializer().deserialize(d["properties_error"] ?? .null)
                            return UploadErrorWithProperties.propertiesError(v)
                        case "other":
                            return UploadErrorWithProperties.other
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The UploadSessionAppendArg struct
    open class UploadSessionAppendArg: CustomStringConvertible {
        /// Contains the upload session ID and the offset.
        public let cursor: Files.UploadSessionCursor
        /// If true, the current session will be closed, at which point you won't be able to call uploadSessionAppendV2
        /// anymore with the current session.
        public let close: Bool
        public init(cursor: Files.UploadSessionCursor, close: Bool = false) {
            self.cursor = cursor
            self.close = close
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionAppendArgSerializer().serialize(self)))"
        }
    }
    open class UploadSessionAppendArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionAppendArg) -> JSON {
            let output = [ 
            "cursor": Files.UploadSessionCursorSerializer().serialize(value.cursor),
            "close": Serialization._BoolSerializer.serialize(value.close),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadSessionAppendArg {
            switch json {
                case .dictionary(let dict):
                    let cursor = Files.UploadSessionCursorSerializer().deserialize(dict["cursor"] ?? .null)
                    let close = Serialization._BoolSerializer.deserialize(dict["close"] ?? .number(0))
                    return UploadSessionAppendArg(cursor: cursor, close: close)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The UploadSessionCursor struct
    open class UploadSessionCursor: CustomStringConvertible {
        /// The upload session ID (returned by uploadSessionStart).
        public let sessionId: String
        /// The amount of data that has been uploaded so far. We use this to make sure upload data isn't lost or
        /// duplicated in the event of a network error.
        public let offset: UInt64
        public init(sessionId: String, offset: UInt64) {
            stringValidator()(sessionId)
            self.sessionId = sessionId
            comparableValidator()(offset)
            self.offset = offset
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionCursorSerializer().serialize(self)))"
        }
    }
    open class UploadSessionCursorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionCursor) -> JSON {
            let output = [ 
            "session_id": Serialization._StringSerializer.serialize(value.sessionId),
            "offset": Serialization._UInt64Serializer.serialize(value.offset),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadSessionCursor {
            switch json {
                case .dictionary(let dict):
                    let sessionId = Serialization._StringSerializer.deserialize(dict["session_id"] ?? .null)
                    let offset = Serialization._UInt64Serializer.deserialize(dict["offset"] ?? .null)
                    return UploadSessionCursor(sessionId: sessionId, offset: offset)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The UploadSessionFinishArg struct
    open class UploadSessionFinishArg: CustomStringConvertible {
        /// Contains the upload session ID and the offset.
        public let cursor: Files.UploadSessionCursor
        /// Contains the path and other optional modifiers for the commit.
        public let commit: Files.CommitInfo
        public init(cursor: Files.UploadSessionCursor, commit: Files.CommitInfo) {
            self.cursor = cursor
            self.commit = commit
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionFinishArgSerializer().serialize(self)))"
        }
    }
    open class UploadSessionFinishArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionFinishArg) -> JSON {
            let output = [ 
            "cursor": Files.UploadSessionCursorSerializer().serialize(value.cursor),
            "commit": Files.CommitInfoSerializer().serialize(value.commit),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadSessionFinishArg {
            switch json {
                case .dictionary(let dict):
                    let cursor = Files.UploadSessionCursorSerializer().deserialize(dict["cursor"] ?? .null)
                    let commit = Files.CommitInfoSerializer().deserialize(dict["commit"] ?? .null)
                    return UploadSessionFinishArg(cursor: cursor, commit: commit)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The UploadSessionFinishBatchArg struct
    open class UploadSessionFinishBatchArg: CustomStringConvertible {
        /// Commit information for each file in the batch.
        public let entries: Array<Files.UploadSessionFinishArg>
        public init(entries: Array<Files.UploadSessionFinishArg>) {
            self.entries = entries
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionFinishBatchArgSerializer().serialize(self)))"
        }
    }
    open class UploadSessionFinishBatchArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionFinishBatchArg) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.UploadSessionFinishArgSerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadSessionFinishBatchArg {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.UploadSessionFinishArgSerializer()).deserialize(dict["entries"] ?? .null)
                    return UploadSessionFinishBatchArg(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The UploadSessionFinishBatchJobStatus union
    public enum UploadSessionFinishBatchJobStatus: CustomStringConvertible {
        /// The asynchronous job is still in progress.
        case inProgress
        /// The uploadSessionFinishBatch has finished.
        case complete(Files.UploadSessionFinishBatchResult)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionFinishBatchJobStatusSerializer().serialize(self)))"
        }
    }
    open class UploadSessionFinishBatchJobStatusSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionFinishBatchJobStatus) -> JSON {
            switch value {
                case .inProgress:
                    var d = [String: JSON]()
                    d[".tag"] = .str("in_progress")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.UploadSessionFinishBatchResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> UploadSessionFinishBatchJobStatus {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "in_progress":
                            return UploadSessionFinishBatchJobStatus.inProgress
                        case "complete":
                            let v = Files.UploadSessionFinishBatchResultSerializer().deserialize(json)
                            return UploadSessionFinishBatchJobStatus.complete(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Result returned by uploadSessionFinishBatch that may either launch an asynchronous job or complete
    /// synchronously.
    public enum UploadSessionFinishBatchLaunch: CustomStringConvertible {
        /// This response indicates that the processing is asynchronous. The string is an id that can be used to obtain
        /// the status of the asynchronous job.
        case asyncJobId(String)
        /// An unspecified error.
        case complete(Files.UploadSessionFinishBatchResult)
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionFinishBatchLaunchSerializer().serialize(self)))"
        }
    }
    open class UploadSessionFinishBatchLaunchSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionFinishBatchLaunch) -> JSON {
            switch value {
                case .asyncJobId(let arg):
                    var d = ["async_job_id": Serialization._StringSerializer.serialize(arg)]
                    d[".tag"] = .str("async_job_id")
                    return .dictionary(d)
                case .complete(let arg):
                    var d = Serialization.getFields(Files.UploadSessionFinishBatchResultSerializer().serialize(arg))
                    d[".tag"] = .str("complete")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> UploadSessionFinishBatchLaunch {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "async_job_id":
                            let v = Serialization._StringSerializer.deserialize(d["async_job_id"] ?? .null)
                            return UploadSessionFinishBatchLaunch.asyncJobId(v)
                        case "complete":
                            let v = Files.UploadSessionFinishBatchResultSerializer().deserialize(json)
                            return UploadSessionFinishBatchLaunch.complete(v)
                        case "other":
                            return UploadSessionFinishBatchLaunch.other
                        default:
                            return UploadSessionFinishBatchLaunch.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The UploadSessionFinishBatchResult struct
    open class UploadSessionFinishBatchResult: CustomStringConvertible {
        /// Each entry in entries in UploadSessionFinishBatchArg will appear at the same position inside entries in
        /// UploadSessionFinishBatchResult.
        public let entries: Array<Files.UploadSessionFinishBatchResultEntry>
        public init(entries: Array<Files.UploadSessionFinishBatchResultEntry>) {
            self.entries = entries
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionFinishBatchResultSerializer().serialize(self)))"
        }
    }
    open class UploadSessionFinishBatchResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionFinishBatchResult) -> JSON {
            let output = [ 
            "entries": ArraySerializer(Files.UploadSessionFinishBatchResultEntrySerializer()).serialize(value.entries),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadSessionFinishBatchResult {
            switch json {
                case .dictionary(let dict):
                    let entries = ArraySerializer(Files.UploadSessionFinishBatchResultEntrySerializer()).deserialize(dict["entries"] ?? .null)
                    return UploadSessionFinishBatchResult(entries: entries)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The UploadSessionFinishBatchResultEntry union
    public enum UploadSessionFinishBatchResultEntry: CustomStringConvertible {
        /// An unspecified error.
        case success(Files.FileMetadata)
        /// An unspecified error.
        case failure(Files.UploadSessionFinishError)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionFinishBatchResultEntrySerializer().serialize(self)))"
        }
    }
    open class UploadSessionFinishBatchResultEntrySerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionFinishBatchResultEntry) -> JSON {
            switch value {
                case .success(let arg):
                    var d = Serialization.getFields(Files.FileMetadataSerializer().serialize(arg))
                    d[".tag"] = .str("success")
                    return .dictionary(d)
                case .failure(let arg):
                    var d = ["failure": Files.UploadSessionFinishErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("failure")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> UploadSessionFinishBatchResultEntry {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "success":
                            let v = Files.FileMetadataSerializer().deserialize(json)
                            return UploadSessionFinishBatchResultEntry.success(v)
                        case "failure":
                            let v = Files.UploadSessionFinishErrorSerializer().deserialize(d["failure"] ?? .null)
                            return UploadSessionFinishBatchResultEntry.failure(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The UploadSessionFinishError union
    public enum UploadSessionFinishError: CustomStringConvertible {
        /// The session arguments are incorrect; the value explains the reason.
        case lookupFailed(Files.UploadSessionLookupError)
        /// Unable to save the uploaded contents to a file. Data has already been appended to the upload session. Please
        /// retry with empty data body and updated offset.
        case path(Files.WriteError)
        /// The supplied property group is invalid. The file has uploaded without property groups.
        case propertiesError(FileProperties.InvalidPropertyGroupError)
        /// The batch request commits files into too many different shared folders. Please limit your batch request to
        /// files contained in a single shared folder.
        case tooManySharedFolderTargets
        /// There are too many write operations happening in the user's Dropbox. You should retry uploading this file.
        case tooManyWriteOperations
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionFinishErrorSerializer().serialize(self)))"
        }
    }
    open class UploadSessionFinishErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionFinishError) -> JSON {
            switch value {
                case .lookupFailed(let arg):
                    var d = ["lookup_failed": Files.UploadSessionLookupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("lookup_failed")
                    return .dictionary(d)
                case .path(let arg):
                    var d = ["path": Files.WriteErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("path")
                    return .dictionary(d)
                case .propertiesError(let arg):
                    var d = ["properties_error": FileProperties.InvalidPropertyGroupErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("properties_error")
                    return .dictionary(d)
                case .tooManySharedFolderTargets:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_shared_folder_targets")
                    return .dictionary(d)
                case .tooManyWriteOperations:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_write_operations")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> UploadSessionFinishError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "lookup_failed":
                            let v = Files.UploadSessionLookupErrorSerializer().deserialize(d["lookup_failed"] ?? .null)
                            return UploadSessionFinishError.lookupFailed(v)
                        case "path":
                            let v = Files.WriteErrorSerializer().deserialize(d["path"] ?? .null)
                            return UploadSessionFinishError.path(v)
                        case "properties_error":
                            let v = FileProperties.InvalidPropertyGroupErrorSerializer().deserialize(d["properties_error"] ?? .null)
                            return UploadSessionFinishError.propertiesError(v)
                        case "too_many_shared_folder_targets":
                            return UploadSessionFinishError.tooManySharedFolderTargets
                        case "too_many_write_operations":
                            return UploadSessionFinishError.tooManyWriteOperations
                        case "other":
                            return UploadSessionFinishError.other
                        default:
                            return UploadSessionFinishError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The UploadSessionLookupError union
    public enum UploadSessionLookupError: CustomStringConvertible {
        /// The upload session ID was not found or has expired. Upload sessions are valid for 48 hours.
        case notFound
        /// The specified offset was incorrect. See the value for the correct offset. This error may occur when a
        /// previous request was received and processed successfully but the client did not receive the response, e.g.
        /// due to a network error.
        case incorrectOffset(Files.UploadSessionOffsetError)
        /// You are attempting to append data to an upload session that has already been closed (i.e. committed).
        case closed
        /// The session must be closed before calling upload_session/finish_batch.
        case notClosed
        /// You can not append to the upload session because the size of a file should not reach the max file size limit
        /// (i.e. 350GB).
        case tooLarge
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionLookupErrorSerializer().serialize(self)))"
        }
    }
    open class UploadSessionLookupErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionLookupError) -> JSON {
            switch value {
                case .notFound:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_found")
                    return .dictionary(d)
                case .incorrectOffset(let arg):
                    var d = Serialization.getFields(Files.UploadSessionOffsetErrorSerializer().serialize(arg))
                    d[".tag"] = .str("incorrect_offset")
                    return .dictionary(d)
                case .closed:
                    var d = [String: JSON]()
                    d[".tag"] = .str("closed")
                    return .dictionary(d)
                case .notClosed:
                    var d = [String: JSON]()
                    d[".tag"] = .str("not_closed")
                    return .dictionary(d)
                case .tooLarge:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_large")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> UploadSessionLookupError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "not_found":
                            return UploadSessionLookupError.notFound
                        case "incorrect_offset":
                            let v = Files.UploadSessionOffsetErrorSerializer().deserialize(json)
                            return UploadSessionLookupError.incorrectOffset(v)
                        case "closed":
                            return UploadSessionLookupError.closed
                        case "not_closed":
                            return UploadSessionLookupError.notClosed
                        case "too_large":
                            return UploadSessionLookupError.tooLarge
                        case "other":
                            return UploadSessionLookupError.other
                        default:
                            return UploadSessionLookupError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The UploadSessionOffsetError struct
    open class UploadSessionOffsetError: CustomStringConvertible {
        /// The offset up to which data has been collected.
        public let correctOffset: UInt64
        public init(correctOffset: UInt64) {
            comparableValidator()(correctOffset)
            self.correctOffset = correctOffset
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionOffsetErrorSerializer().serialize(self)))"
        }
    }
    open class UploadSessionOffsetErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionOffsetError) -> JSON {
            let output = [ 
            "correct_offset": Serialization._UInt64Serializer.serialize(value.correctOffset),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadSessionOffsetError {
            switch json {
                case .dictionary(let dict):
                    let correctOffset = Serialization._UInt64Serializer.deserialize(dict["correct_offset"] ?? .null)
                    return UploadSessionOffsetError(correctOffset: correctOffset)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The UploadSessionStartArg struct
    open class UploadSessionStartArg: CustomStringConvertible {
        /// If true, the current session will be closed, at which point you won't be able to call uploadSessionAppendV2
        /// anymore with the current session.
        public let close: Bool
        public init(close: Bool = false) {
            self.close = close
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionStartArgSerializer().serialize(self)))"
        }
    }
    open class UploadSessionStartArgSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionStartArg) -> JSON {
            let output = [ 
            "close": Serialization._BoolSerializer.serialize(value.close),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadSessionStartArg {
            switch json {
                case .dictionary(let dict):
                    let close = Serialization._BoolSerializer.deserialize(dict["close"] ?? .number(0))
                    return UploadSessionStartArg(close: close)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The UploadSessionStartResult struct
    open class UploadSessionStartResult: CustomStringConvertible {
        /// A unique identifier for the upload session. Pass this to uploadSessionAppendV2 and uploadSessionFinish.
        public let sessionId: String
        public init(sessionId: String) {
            stringValidator()(sessionId)
            self.sessionId = sessionId
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadSessionStartResultSerializer().serialize(self)))"
        }
    }
    open class UploadSessionStartResultSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadSessionStartResult) -> JSON {
            let output = [ 
            "session_id": Serialization._StringSerializer.serialize(value.sessionId),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadSessionStartResult {
            switch json {
                case .dictionary(let dict):
                    let sessionId = Serialization._StringSerializer.deserialize(dict["session_id"] ?? .null)
                    return UploadSessionStartResult(sessionId: sessionId)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The UploadWriteFailed struct
    open class UploadWriteFailed: CustomStringConvertible {
        /// The reason why the file couldn't be saved.
        public let reason: Files.WriteError
        /// The upload session ID; data has already been uploaded to the corresponding upload session and this ID may be
        /// used to retry the commit with uploadSessionFinish.
        public let uploadSessionId: String
        public init(reason: Files.WriteError, uploadSessionId: String) {
            self.reason = reason
            stringValidator()(uploadSessionId)
            self.uploadSessionId = uploadSessionId
        }
        open var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(UploadWriteFailedSerializer().serialize(self)))"
        }
    }
    open class UploadWriteFailedSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: UploadWriteFailed) -> JSON {
            let output = [ 
            "reason": Files.WriteErrorSerializer().serialize(value.reason),
            "upload_session_id": Serialization._StringSerializer.serialize(value.uploadSessionId),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> UploadWriteFailed {
            switch json {
                case .dictionary(let dict):
                    let reason = Files.WriteErrorSerializer().deserialize(dict["reason"] ?? .null)
                    let uploadSessionId = Serialization._StringSerializer.deserialize(dict["upload_session_id"] ?? .null)
                    return UploadWriteFailed(reason: reason, uploadSessionId: uploadSessionId)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// Metadata for a video.
    open class VideoMetadata: Files.MediaMetadata {
        /// The duration of the video in milliseconds.
        public let duration: UInt64?
        public init(dimensions: Files.Dimensions? = nil, location: Files.GpsCoordinates? = nil, timeTaken: Date? = nil, duration: UInt64? = nil) {
            nullableValidator(comparableValidator())(duration)
            self.duration = duration
            super.init(dimensions: dimensions, location: location, timeTaken: timeTaken)
        }
        open override var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(VideoMetadataSerializer().serialize(self)))"
        }
    }
    open class VideoMetadataSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: VideoMetadata) -> JSON {
            let output = [ 
            "dimensions": NullableSerializer(Files.DimensionsSerializer()).serialize(value.dimensions),
            "location": NullableSerializer(Files.GpsCoordinatesSerializer()).serialize(value.location),
            "time_taken": NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).serialize(value.timeTaken),
            "duration": NullableSerializer(Serialization._UInt64Serializer).serialize(value.duration),
            ]
            return .dictionary(output)
        }
        open func deserialize(_ json: JSON) -> VideoMetadata {
            switch json {
                case .dictionary(let dict):
                    let dimensions = NullableSerializer(Files.DimensionsSerializer()).deserialize(dict["dimensions"] ?? .null)
                    let location = NullableSerializer(Files.GpsCoordinatesSerializer()).deserialize(dict["location"] ?? .null)
                    let timeTaken = NullableSerializer(NSDateSerializer("%Y-%m-%dT%H:%M:%SZ")).deserialize(dict["time_taken"] ?? .null)
                    let duration = NullableSerializer(Serialization._UInt64Serializer).deserialize(dict["duration"] ?? .null)
                    return VideoMetadata(dimensions: dimensions, location: location, timeTaken: timeTaken, duration: duration)
                default:
                    fatalError("Type error deserializing")
            }
        }
    }
    /// The WriteConflictError union
    public enum WriteConflictError: CustomStringConvertible {
        /// There's a file in the way.
        case file
        /// There's a folder in the way.
        case folder
        /// There's a file at an ancestor path, so we couldn't create the required parent folders.
        case fileAncestor
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(WriteConflictErrorSerializer().serialize(self)))"
        }
    }
    open class WriteConflictErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: WriteConflictError) -> JSON {
            switch value {
                case .file:
                    var d = [String: JSON]()
                    d[".tag"] = .str("file")
                    return .dictionary(d)
                case .folder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("folder")
                    return .dictionary(d)
                case .fileAncestor:
                    var d = [String: JSON]()
                    d[".tag"] = .str("file_ancestor")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> WriteConflictError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "file":
                            return WriteConflictError.file
                        case "folder":
                            return WriteConflictError.folder
                        case "file_ancestor":
                            return WriteConflictError.fileAncestor
                        case "other":
                            return WriteConflictError.other
                        default:
                            return WriteConflictError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// The WriteError union
    public enum WriteError: CustomStringConvertible {
        /// The given path does not satisfy the required path format. Please refer to the Path formats documentation
        /// https://www.dropbox.com/developers/documentation/http/documentation#path-formats for more information.
        case malformedPath(String?)
        /// Couldn't write to the target path because there was something in the way.
        case conflict(Files.WriteConflictError)
        /// The user doesn't have permissions to write to the target location.
        case noWritePermission
        /// The user doesn't have enough available space (bytes) to write more data.
        case insufficientSpace
        /// Dropbox will not save the file or folder because of its name.
        case disallowedName
        /// This endpoint cannot move or delete team folders.
        case teamFolder
        /// There are too many write operations in user's Dropbox. Please retry this request.
        case tooManyWriteOperations
        /// An unspecified error.
        case other
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(WriteErrorSerializer().serialize(self)))"
        }
    }
    open class WriteErrorSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: WriteError) -> JSON {
            switch value {
                case .malformedPath(let arg):
                    var d = ["malformed_path": NullableSerializer(Serialization._StringSerializer).serialize(arg)]
                    d[".tag"] = .str("malformed_path")
                    return .dictionary(d)
                case .conflict(let arg):
                    var d = ["conflict": Files.WriteConflictErrorSerializer().serialize(arg)]
                    d[".tag"] = .str("conflict")
                    return .dictionary(d)
                case .noWritePermission:
                    var d = [String: JSON]()
                    d[".tag"] = .str("no_write_permission")
                    return .dictionary(d)
                case .insufficientSpace:
                    var d = [String: JSON]()
                    d[".tag"] = .str("insufficient_space")
                    return .dictionary(d)
                case .disallowedName:
                    var d = [String: JSON]()
                    d[".tag"] = .str("disallowed_name")
                    return .dictionary(d)
                case .teamFolder:
                    var d = [String: JSON]()
                    d[".tag"] = .str("team_folder")
                    return .dictionary(d)
                case .tooManyWriteOperations:
                    var d = [String: JSON]()
                    d[".tag"] = .str("too_many_write_operations")
                    return .dictionary(d)
                case .other:
                    var d = [String: JSON]()
                    d[".tag"] = .str("other")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> WriteError {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "malformed_path":
                            let v = NullableSerializer(Serialization._StringSerializer).deserialize(d["malformed_path"] ?? .null)
                            return WriteError.malformedPath(v)
                        case "conflict":
                            let v = Files.WriteConflictErrorSerializer().deserialize(d["conflict"] ?? .null)
                            return WriteError.conflict(v)
                        case "no_write_permission":
                            return WriteError.noWritePermission
                        case "insufficient_space":
                            return WriteError.insufficientSpace
                        case "disallowed_name":
                            return WriteError.disallowedName
                        case "team_folder":
                            return WriteError.teamFolder
                        case "too_many_write_operations":
                            return WriteError.tooManyWriteOperations
                        case "other":
                            return WriteError.other
                        default:
                            return WriteError.other
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Your intent when writing a file to some path. This is used to determine what constitutes a conflict and what the
    /// autorename strategy is. In some situations, the conflict behavior is identical: (a) If the target path doesn't
    /// refer to anything, the file is always written; no conflict. (b) If the target path refers to a folder, it's
    /// always a conflict. (c) If the target path refers to a file with identical contents, nothing gets written; no
    /// conflict. The conflict checking differs in the case where there's a file at the target path with contents
    /// different from the contents you're trying to write.
    public enum WriteMode: CustomStringConvertible {
        /// Do not overwrite an existing file if there is a conflict. The autorename strategy is to append a number to
        /// the file name. For example, "document.txt" might become "document (2).txt".
        case add
        /// Always overwrite the existing file. The autorename strategy is the same as it is for add.
        case overwrite
        /// Overwrite if the given "rev" matches the existing file's "rev". The autorename strategy is to append the
        /// string "conflicted copy" to the file name. For example, "document.txt" might become "document (conflicted
        /// copy).txt" or "document (Panda's conflicted copy).txt".
        case update(String)
        public var description: String {
            return "\(SerializeUtil.prepareJSONForSerialization(WriteModeSerializer().serialize(self)))"
        }
    }
    open class WriteModeSerializer: JSONSerializer {
        public init() { }
        open func serialize(_ value: WriteMode) -> JSON {
            switch value {
                case .add:
                    var d = [String: JSON]()
                    d[".tag"] = .str("add")
                    return .dictionary(d)
                case .overwrite:
                    var d = [String: JSON]()
                    d[".tag"] = .str("overwrite")
                    return .dictionary(d)
                case .update(let arg):
                    var d = ["update": Serialization._StringSerializer.serialize(arg)]
                    d[".tag"] = .str("update")
                    return .dictionary(d)
            }
        }
        open func deserialize(_ json: JSON) -> WriteMode {
            switch json {
                case .dictionary(let d):
                    let tag = Serialization.getTag(d)
                    switch tag {
                        case "add":
                            return WriteMode.add
                        case "overwrite":
                            return WriteMode.overwrite
                        case "update":
                            let v = Serialization._StringSerializer.deserialize(d["update"] ?? .null)
                            return WriteMode.update(v)
                        default:
                            fatalError("Unknown tag \(tag)")
                    }
                default:
                    fatalError("Failed to deserialize")
            }
        }
    }
    /// Stone Route Objects
    static let alphaGetMetadata = Route(
        name: "alpha/get_metadata",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Files.AlphaGetMetadataArgSerializer(),
        responseSerializer: Files.MetadataSerializer(),
        errorSerializer: Files.AlphaGetMetadataErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let alphaUpload = Route(
        name: "alpha/upload",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Files.CommitInfoWithPropertiesSerializer(),
        responseSerializer: Files.FileMetadataSerializer(),
        errorSerializer: Files.UploadErrorWithPropertiesSerializer(),
        attrs: ["host": "content",
                "style": "upload"]
    )
    static let copyV2 = Route(
        name: "copy",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.RelocationArgSerializer(),
        responseSerializer: Files.RelocationResultSerializer(),
        errorSerializer: Files.RelocationErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let copy = Route(
        name: "copy",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Files.RelocationArgSerializer(),
        responseSerializer: Files.MetadataSerializer(),
        errorSerializer: Files.RelocationErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let copyBatchV2 = Route(
        name: "copy_batch",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.RelocationBatchArgBaseSerializer(),
        responseSerializer: Files.RelocationBatchV2LaunchSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let copyBatch = Route(
        name: "copy_batch",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Files.RelocationBatchArgSerializer(),
        responseSerializer: Files.RelocationBatchLaunchSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let copyBatchCheckV2 = Route(
        name: "copy_batch/check",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Async.PollArgSerializer(),
        responseSerializer: Files.RelocationBatchV2JobStatusSerializer(),
        errorSerializer: Async.PollErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let copyBatchCheck = Route(
        name: "copy_batch/check",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Async.PollArgSerializer(),
        responseSerializer: Files.RelocationBatchJobStatusSerializer(),
        errorSerializer: Async.PollErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let copyReferenceGet = Route(
        name: "copy_reference/get",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.GetCopyReferenceArgSerializer(),
        responseSerializer: Files.GetCopyReferenceResultSerializer(),
        errorSerializer: Files.GetCopyReferenceErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let copyReferenceSave = Route(
        name: "copy_reference/save",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.SaveCopyReferenceArgSerializer(),
        responseSerializer: Files.SaveCopyReferenceResultSerializer(),
        errorSerializer: Files.SaveCopyReferenceErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let createFolderV2 = Route(
        name: "create_folder",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.CreateFolderArgSerializer(),
        responseSerializer: Files.CreateFolderResultSerializer(),
        errorSerializer: Files.CreateFolderErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let createFolder = Route(
        name: "create_folder",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Files.CreateFolderArgSerializer(),
        responseSerializer: Files.FolderMetadataSerializer(),
        errorSerializer: Files.CreateFolderErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let createFolderBatch = Route(
        name: "create_folder_batch",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.CreateFolderBatchArgSerializer(),
        responseSerializer: Files.CreateFolderBatchLaunchSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let createFolderBatchCheck = Route(
        name: "create_folder_batch/check",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Async.PollArgSerializer(),
        responseSerializer: Files.CreateFolderBatchJobStatusSerializer(),
        errorSerializer: Async.PollErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let deleteV2 = Route(
        name: "delete",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.DeleteArgSerializer(),
        responseSerializer: Files.DeleteResultSerializer(),
        errorSerializer: Files.DeleteErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let delete = Route(
        name: "delete",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Files.DeleteArgSerializer(),
        responseSerializer: Files.MetadataSerializer(),
        errorSerializer: Files.DeleteErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let deleteBatch = Route(
        name: "delete_batch",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.DeleteBatchArgSerializer(),
        responseSerializer: Files.DeleteBatchLaunchSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let deleteBatchCheck = Route(
        name: "delete_batch/check",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Async.PollArgSerializer(),
        responseSerializer: Files.DeleteBatchJobStatusSerializer(),
        errorSerializer: Async.PollErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let download = Route(
        name: "download",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.DownloadArgSerializer(),
        responseSerializer: Files.FileMetadataSerializer(),
        errorSerializer: Files.DownloadErrorSerializer(),
        attrs: ["host": "content",
                "style": "download"]
    )
    static let downloadZip = Route(
        name: "download_zip",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.DownloadZipArgSerializer(),
        responseSerializer: Files.DownloadZipResultSerializer(),
        errorSerializer: Files.DownloadZipErrorSerializer(),
        attrs: ["host": "content",
                "style": "download"]
    )
    static let export = Route(
        name: "export",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.ExportArgSerializer(),
        responseSerializer: Files.ExportResultSerializer(),
        errorSerializer: Files.ExportErrorSerializer(),
        attrs: ["host": "content",
                "style": "download"]
    )
    static let getMetadata = Route(
        name: "get_metadata",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.GetMetadataArgSerializer(),
        responseSerializer: Files.MetadataSerializer(),
        errorSerializer: Files.GetMetadataErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let getPreview = Route(
        name: "get_preview",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.PreviewArgSerializer(),
        responseSerializer: Files.FileMetadataSerializer(),
        errorSerializer: Files.PreviewErrorSerializer(),
        attrs: ["host": "content",
                "style": "download"]
    )
    static let getTemporaryLink = Route(
        name: "get_temporary_link",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.GetTemporaryLinkArgSerializer(),
        responseSerializer: Files.GetTemporaryLinkResultSerializer(),
        errorSerializer: Files.GetTemporaryLinkErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let getTemporaryUploadLink = Route(
        name: "get_temporary_upload_link",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.GetTemporaryUploadLinkArgSerializer(),
        responseSerializer: Files.GetTemporaryUploadLinkResultSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let getThumbnail = Route(
        name: "get_thumbnail",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.ThumbnailArgSerializer(),
        responseSerializer: Files.FileMetadataSerializer(),
        errorSerializer: Files.ThumbnailErrorSerializer(),
        attrs: ["host": "content",
                "style": "download"]
    )
    static let getThumbnailBatch = Route(
        name: "get_thumbnail_batch",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.GetThumbnailBatchArgSerializer(),
        responseSerializer: Files.GetThumbnailBatchResultSerializer(),
        errorSerializer: Files.GetThumbnailBatchErrorSerializer(),
        attrs: ["host": "content",
                "style": "rpc"]
    )
    static let listFolder = Route(
        name: "list_folder",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.ListFolderArgSerializer(),
        responseSerializer: Files.ListFolderResultSerializer(),
        errorSerializer: Files.ListFolderErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let listFolderContinue = Route(
        name: "list_folder/continue",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.ListFolderContinueArgSerializer(),
        responseSerializer: Files.ListFolderResultSerializer(),
        errorSerializer: Files.ListFolderContinueErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let listFolderGetLatestCursor = Route(
        name: "list_folder/get_latest_cursor",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.ListFolderArgSerializer(),
        responseSerializer: Files.ListFolderGetLatestCursorResultSerializer(),
        errorSerializer: Files.ListFolderErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let listFolderLongpoll = Route(
        name: "list_folder/longpoll",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.ListFolderLongpollArgSerializer(),
        responseSerializer: Files.ListFolderLongpollResultSerializer(),
        errorSerializer: Files.ListFolderLongpollErrorSerializer(),
        attrs: ["host": "notify",
                "style": "rpc"]
    )
    static let listRevisions = Route(
        name: "list_revisions",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.ListRevisionsArgSerializer(),
        responseSerializer: Files.ListRevisionsResultSerializer(),
        errorSerializer: Files.ListRevisionsErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let moveV2 = Route(
        name: "move",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.RelocationArgSerializer(),
        responseSerializer: Files.RelocationResultSerializer(),
        errorSerializer: Files.RelocationErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let move = Route(
        name: "move",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Files.RelocationArgSerializer(),
        responseSerializer: Files.MetadataSerializer(),
        errorSerializer: Files.RelocationErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let moveBatchV2 = Route(
        name: "move_batch",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.MoveBatchArgSerializer(),
        responseSerializer: Files.RelocationBatchV2LaunchSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let moveBatch = Route(
        name: "move_batch",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.RelocationBatchArgSerializer(),
        responseSerializer: Files.RelocationBatchLaunchSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let moveBatchCheckV2 = Route(
        name: "move_batch/check",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Async.PollArgSerializer(),
        responseSerializer: Files.RelocationBatchV2JobStatusSerializer(),
        errorSerializer: Async.PollErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let moveBatchCheck = Route(
        name: "move_batch/check",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Async.PollArgSerializer(),
        responseSerializer: Files.RelocationBatchJobStatusSerializer(),
        errorSerializer: Async.PollErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let permanentlyDelete = Route(
        name: "permanently_delete",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.DeleteArgSerializer(),
        responseSerializer: Serialization._VoidSerializer,
        errorSerializer: Files.DeleteErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let propertiesAdd = Route(
        name: "properties/add",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: FileProperties.AddPropertiesArgSerializer(),
        responseSerializer: Serialization._VoidSerializer,
        errorSerializer: FileProperties.AddPropertiesErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let propertiesOverwrite = Route(
        name: "properties/overwrite",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: FileProperties.OverwritePropertyGroupArgSerializer(),
        responseSerializer: Serialization._VoidSerializer,
        errorSerializer: FileProperties.InvalidPropertyGroupErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let propertiesRemove = Route(
        name: "properties/remove",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: FileProperties.RemovePropertiesArgSerializer(),
        responseSerializer: Serialization._VoidSerializer,
        errorSerializer: FileProperties.RemovePropertiesErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let propertiesTemplateGet = Route(
        name: "properties/template/get",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: FileProperties.GetTemplateArgSerializer(),
        responseSerializer: FileProperties.GetTemplateResultSerializer(),
        errorSerializer: FileProperties.TemplateErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let propertiesTemplateList = Route(
        name: "properties/template/list",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Serialization._VoidSerializer,
        responseSerializer: FileProperties.ListTemplateResultSerializer(),
        errorSerializer: FileProperties.TemplateErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let propertiesUpdate = Route(
        name: "properties/update",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: FileProperties.UpdatePropertiesArgSerializer(),
        responseSerializer: Serialization._VoidSerializer,
        errorSerializer: FileProperties.UpdatePropertiesErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let restore = Route(
        name: "restore",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.RestoreArgSerializer(),
        responseSerializer: Files.FileMetadataSerializer(),
        errorSerializer: Files.RestoreErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let saveUrl = Route(
        name: "save_url",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.SaveUrlArgSerializer(),
        responseSerializer: Files.SaveUrlResultSerializer(),
        errorSerializer: Files.SaveUrlErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let saveUrlCheckJobStatus = Route(
        name: "save_url/check_job_status",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Async.PollArgSerializer(),
        responseSerializer: Files.SaveUrlJobStatusSerializer(),
        errorSerializer: Async.PollErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let search = Route(
        name: "search",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.SearchArgSerializer(),
        responseSerializer: Files.SearchResultSerializer(),
        errorSerializer: Files.SearchErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let upload = Route(
        name: "upload",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.CommitInfoSerializer(),
        responseSerializer: Files.FileMetadataSerializer(),
        errorSerializer: Files.UploadErrorSerializer(),
        attrs: ["host": "content",
                "style": "upload"]
    )
    static let uploadSessionAppendV2 = Route(
        name: "upload_session/append",
        version: 2,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.UploadSessionAppendArgSerializer(),
        responseSerializer: Serialization._VoidSerializer,
        errorSerializer: Files.UploadSessionLookupErrorSerializer(),
        attrs: ["host": "content",
                "style": "upload"]
    )
    static let uploadSessionAppend = Route(
        name: "upload_session/append",
        version: 1,
        namespace: "files",
        deprecated: true,
        argSerializer: Files.UploadSessionCursorSerializer(),
        responseSerializer: Serialization._VoidSerializer,
        errorSerializer: Files.UploadSessionLookupErrorSerializer(),
        attrs: ["host": "content",
                "style": "upload"]
    )
    static let uploadSessionFinish = Route(
        name: "upload_session/finish",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.UploadSessionFinishArgSerializer(),
        responseSerializer: Files.FileMetadataSerializer(),
        errorSerializer: Files.UploadSessionFinishErrorSerializer(),
        attrs: ["host": "content",
                "style": "upload"]
    )
    static let uploadSessionFinishBatch = Route(
        name: "upload_session/finish_batch",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.UploadSessionFinishBatchArgSerializer(),
        responseSerializer: Files.UploadSessionFinishBatchLaunchSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let uploadSessionFinishBatchCheck = Route(
        name: "upload_session/finish_batch/check",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Async.PollArgSerializer(),
        responseSerializer: Files.UploadSessionFinishBatchJobStatusSerializer(),
        errorSerializer: Async.PollErrorSerializer(),
        attrs: ["host": "api",
                "style": "rpc"]
    )
    static let uploadSessionStart = Route(
        name: "upload_session/start",
        version: 1,
        namespace: "files",
        deprecated: false,
        argSerializer: Files.UploadSessionStartArgSerializer(),
        responseSerializer: Files.UploadSessionStartResultSerializer(),
        errorSerializer: Serialization._VoidSerializer,
        attrs: ["host": "content",
                "style": "upload"]
    )
}
 | 
	mit | 
| 
	MxABC/LBXAlertAction | 
	AlertAction/UIWindow+LBXHierarchy.swift | 
	1 | 
	1522 | 
	//
//  AlertAction.swift
//
//
//  Created by lbxia on 16/6/20.
//  Copyright © 2016年 lbx. All rights reserved.
//
import UIKit
/** @abstract UIWindow hierarchy category.  */
public extension UIWindow {
    /** @return Returns the current Top Most ViewController in hierarchy.   */
     public func topController()->UIViewController? {
        
        var topController = rootViewController
        
        while let presentedController = topController?.presentedViewController {
            topController = presentedController
        }
        
        return topController
    }
    
    /** @return Returns the topViewController in stack of topController.    */
    public func currentTopViewController()->UIViewController? {
        
        var currentViewController = topController()
        
        while currentViewController != nil
            && currentViewController is UITabBarController
            && (currentViewController as! UITabBarController).selectedViewController != nil
        {
            currentViewController = (currentViewController as! UITabBarController).selectedViewController
        }
        
        while currentViewController != nil
            && currentViewController is UINavigationController
            && (currentViewController as! UINavigationController).topViewController != nil
        {
                
            currentViewController = (currentViewController as! UINavigationController).topViewController
        }
        return currentViewController
    }
}
 | 
	mit | 
| 
	ahoppen/swift | 
	test/SILGen/Inputs/struct_with_initializer.swift | 
	51 | 
	168 | 
	struct HasInitValue {
  var x = 10
  var y: String = ""
}
struct HasPrivateInitValue {
  private var x = 10
}
public struct PublicStructHasInitValue {
  var x = 10
}
 | 
	apache-2.0 | 
| 
	KeithPiTsui/Pavers | 
	Pavers/Sources/CryptoSwift/String+Extension.swift | 
	2 | 
	2830 | 
	//
//  StringExtension.swift
//  CryptoSwift
//
//  Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
//  This software is provided 'as-is', without any express or implied warranty.
//
//  In no event will the authors be held liable for any damages arising from the use of this software.
//
//  Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
//  - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
//  - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
//  - This notice may not be removed or altered from any source or binary distribution.
//
/** String extension */
extension String {
    public var bytes: Array<UInt8> {
        return data(using: String.Encoding.utf8, allowLossyConversion: true)?.bytes ?? Array(utf8)
    }
    public func md5() -> String {
        return bytes.md5().toHexString()
    }
    public func sha1() -> String {
        return bytes.sha1().toHexString()
    }
    public func sha224() -> String {
        return bytes.sha224().toHexString()
    }
    public func sha256() -> String {
        return bytes.sha256().toHexString()
    }
    public func sha384() -> String {
        return bytes.sha384().toHexString()
    }
    public func sha512() -> String {
        return bytes.sha512().toHexString()
    }
    public func sha3(_ variant: SHA3.Variant) -> String {
        return bytes.sha3(variant).toHexString()
    }
    public func crc32(seed: UInt32? = nil, reflect: Bool = true) -> String {
        return bytes.crc32(seed: seed, reflect: reflect).bytes().toHexString()
    }
    public func crc16(seed: UInt16? = nil) -> String {
        return bytes.crc16(seed: seed).bytes().toHexString()
    }
    /// - parameter cipher: Instance of `Cipher`
    /// - returns: hex string of bytes
    public func encrypt(cipher: Cipher) throws -> String {
        return try bytes.encrypt(cipher: cipher).toHexString()
    }
    /// - parameter cipher: Instance of `Cipher`
    /// - returns: base64 encoded string of encrypted bytes
    public func encryptToBase64(cipher: Cipher) throws -> String? {
        return try bytes.encrypt(cipher: cipher).toBase64()
    }
    // decrypt() does not make sense for String
    /// - parameter authenticator: Instance of `Authenticator`
    /// - returns: hex string of string
    public func authenticate<A: Authenticator>(with authenticator: A) throws -> String {
        return try bytes.authenticate(with: authenticator).toHexString()
    }
}
 | 
	mit | 
| 
	JGiola/swift | 
	test/SILGen/noimplicitcopy_attr.swift | 
	1 | 
	898 | 
	// RUN: %target-swift-emit-silgen -enable-experimental-move-only -parse-stdlib -disable-availability-checking %s | %FileCheck %s
// RUN: %target-swift-emit-sil -enable-experimental-move-only -parse-stdlib -disable-availability-checking %s | %FileCheck -check-prefix=CHECK-SIL %s
// RUN: %target-swift-emit-sil -O -enable-experimental-move-only -Xllvm -sil-disable-pass=FunctionSignatureOpts -parse-stdlib -disable-availability-checking %s | %FileCheck -check-prefix=CHECK-SIL %s
public class Klass {
    func doSomething() {}
}
// CHECK: bb0(%0 : @noImplicitCopy @guaranteed $Klass):
// CHECK-SIL: bb0(%0 : @noImplicitCopy $Klass):
public func arguments(@_noImplicitCopy _ x: Klass) {
    x.doSomething()
}
// CHECK: bb0(%0 : @noImplicitCopy @owned $Klass):
// CHECK-SIL: bb0(%0 : @noImplicitCopy $Klass):
public func argumentsOwned(@_noImplicitCopy _ x: __owned Klass) {
    x.doSomething()
}
 | 
	apache-2.0 | 
| 
	JackieXie168/skim | 
	vendorsrc/andymatuschak/Sparkle/Tests/SUFileManagerTest.swift | 
	3 | 
	17557 | 
	//
//  SUFileManagerTest.swift
//  Sparkle
//
//  Created by Mayur Pawashe on 9/26/15.
//  Copyright © 2015 Sparkle Project. All rights reserved.
//
import XCTest
class SUFileManagerTest: XCTestCase
{
    func makeTempFiles(_ testBlock: (SUFileManager, URL, URL, URL, URL, URL, URL) -> Void)
    {
        let fileManager = SUFileManager.default()
        
        let tempDirectoryURL = (try! fileManager.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory())))
        
        defer {
            try! fileManager.removeItem(at: tempDirectoryURL)
        }
        
        let ordinaryFileURL = tempDirectoryURL.appendingPathComponent("a file written by sparkles unit tests")
        try! "foo".data(using: String.Encoding.utf8)!.write(to: ordinaryFileURL, options: .atomic)
        
        let directoryURL = tempDirectoryURL.appendingPathComponent("a directory written by sparkles unit tests")
        try! FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: false, attributes: nil)
        
        let fileInDirectoryURL = directoryURL.appendingPathComponent("a file inside a directory written by sparkles unit tests")
        try! "bar baz".data(using: String.Encoding.utf8)!.write(to: fileInDirectoryURL, options: .atomic)
        
        let validSymlinkURL = tempDirectoryURL.appendingPathComponent("symlink test")
        try! FileManager.default.createSymbolicLink(at: validSymlinkURL, withDestinationURL: directoryURL)
        
        let invalidSymlinkURL = tempDirectoryURL.appendingPathComponent("symlink test 2")
        try! FileManager.default.createSymbolicLink(at: invalidSymlinkURL, withDestinationURL: (tempDirectoryURL.appendingPathComponent("does not exist")))
        
        testBlock(fileManager, tempDirectoryURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL)
    }
    
    func testMoveFiles()
    {
        makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
            XCTAssertNil(try? fileManager.moveItem(at: ordinaryFileURL, to: directoryURL))
            XCTAssertNil(try? fileManager.moveItem(at: ordinaryFileURL, to: directoryURL.appendingPathComponent("foo").appendingPathComponent("bar")))
            XCTAssertNil(try? fileManager.moveItem(at: rootURL.appendingPathComponent("does not exist"), to: directoryURL))
            
            let newFileURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new file"))
            try! fileManager.moveItem(at: ordinaryFileURL, to: newFileURL)
            XCTAssertFalse(fileManager._itemExists(at: ordinaryFileURL))
            XCTAssertTrue(fileManager._itemExists(at: newFileURL))
            
            let newValidSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new symlink"))
            try! fileManager.moveItem(at: validSymlinkURL, to: newValidSymlinkURL)
            XCTAssertFalse(fileManager._itemExists(at: validSymlinkURL))
            XCTAssertTrue(fileManager._itemExists(at: newValidSymlinkURL))
            XCTAssertTrue(fileManager._itemExists(at: directoryURL))
            
            let newInvalidSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new invalid symlink"))
            try! fileManager.moveItem(at: invalidSymlinkURL, to: newInvalidSymlinkURL)
            XCTAssertFalse(fileManager._itemExists(at: invalidSymlinkURL))
            XCTAssertTrue(fileManager._itemExists(at: newValidSymlinkURL))
            
            let newDirectoryURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new directory"))
            try! fileManager.moveItem(at: directoryURL, to: newDirectoryURL)
            XCTAssertFalse(fileManager._itemExists(at: directoryURL))
            XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL))
            XCTAssertFalse(fileManager._itemExists(at: fileInDirectoryURL))
            XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL.appendingPathComponent(fileInDirectoryURL.lastPathComponent)))
        }
    }
    
    func testCopyFiles()
    {
        makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
            XCTAssertNil(try? fileManager.copyItem(at: ordinaryFileURL, to: directoryURL))
            XCTAssertNil(try? fileManager.copyItem(at: ordinaryFileURL, to: directoryURL.appendingPathComponent("foo").appendingPathComponent("bar")))
            XCTAssertNil(try? fileManager.copyItem(at: rootURL.appendingPathComponent("does not exist"), to: directoryURL))
            
            let newFileURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new file"))
            try! fileManager.copyItem(at: ordinaryFileURL, to: newFileURL)
            XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL))
            XCTAssertTrue(fileManager._itemExists(at: newFileURL))
            
            let newSymlinkURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new symlink file"))
            try! fileManager.copyItem(at: invalidSymlinkURL, to: newSymlinkURL)
            XCTAssertTrue(fileManager._itemExists(at: newSymlinkURL))
            
            let newDirectoryURL = (ordinaryFileURL.deletingLastPathComponent().appendingPathComponent("new directory"))
            try! fileManager.copyItem(at: directoryURL, to: newDirectoryURL)
            XCTAssertTrue(fileManager._itemExists(at: directoryURL))
            XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL))
            XCTAssertTrue(fileManager._itemExists(at: fileInDirectoryURL))
            XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL.appendingPathComponent(fileInDirectoryURL.lastPathComponent)))
        }
    }
    func testRemoveFiles()
    {
        makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
            XCTAssertNil(try? fileManager.removeItem(at: rootURL.appendingPathComponent("does not exist")))
            
            try! fileManager.removeItem(at: ordinaryFileURL)
            XCTAssertFalse(fileManager._itemExists(at: ordinaryFileURL))
            
            try! fileManager.removeItem(at: validSymlinkURL)
            XCTAssertFalse(fileManager._itemExists(at: validSymlinkURL))
            XCTAssertTrue(fileManager._itemExists(at: directoryURL))
            
            try! fileManager.removeItem(at: directoryURL)
            XCTAssertFalse(fileManager._itemExists(at: directoryURL))
            XCTAssertFalse(fileManager._itemExists(at: fileInDirectoryURL))
        }
    }
    
    func testReleaseFilesFromQuarantine()
    {
        makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
            try! fileManager.releaseItemFromQuarantine(atRootURL: ordinaryFileURL)
            try! fileManager.releaseItemFromQuarantine(atRootURL: directoryURL)
            try! fileManager.releaseItemFromQuarantine(atRootURL: validSymlinkURL)
            
            let quarantineData = "does not really matter what is here".cString(using: String.Encoding.utf8)!
            let quarantineDataLength = Int(strlen(quarantineData))
            
            XCTAssertEqual(0, setxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE))
            XCTAssertGreaterThan(getxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0)
            
            try! fileManager.releaseItemFromQuarantine(atRootURL: ordinaryFileURL)
            XCTAssertEqual(-1, getxattr(ordinaryFileURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
            
            XCTAssertEqual(0, setxattr(directoryURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE))
            XCTAssertGreaterThan(getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0)
            
            XCTAssertEqual(0, setxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, quarantineData, quarantineDataLength, 0, XATTR_CREATE))
            XCTAssertGreaterThan(getxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0)
            
            // Extended attributes can't be set on symbolic links currently
            try! fileManager.releaseItemFromQuarantine(atRootURL: validSymlinkURL)
            XCTAssertGreaterThan(getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW), 0)
            XCTAssertEqual(-1, getxattr(validSymlinkURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
            
            try! fileManager.releaseItemFromQuarantine(atRootURL: directoryURL)
            
            XCTAssertEqual(-1, getxattr(directoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
            XCTAssertEqual(-1, getxattr(fileInDirectoryURL.path, SUAppleQuarantineIdentifier, nil, 0, 0, XATTR_NOFOLLOW))
        }
    }
    
    func groupIDAtPath(_ path: String) -> gid_t
    {
        let attributes = try! FileManager.default.attributesOfItem(atPath: path)
        let groupID = attributes[FileAttributeKey.groupOwnerAccountID] as! NSNumber
        return groupID.uint32Value
    }
    
    // Only the super user can alter user IDs, so changing user IDs is not tested here
    // Instead we try to change the group ID - we just have to be a member of that group
    func testAlterFilesGroupID()
    {
        makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
            XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItem(atRootURL: ordinaryFileURL, toMatch: rootURL.appendingPathComponent("does not exist")))
            
            XCTAssertNil(try? fileManager.changeOwnerAndGroupOfItem(atRootURL: rootURL.appendingPathComponent("does not exist"), toMatch: ordinaryFileURL))
            
            let everyoneGroup = getgrnam("everyone")
            let everyoneGroupID = everyoneGroup?.pointee.gr_gid
            
            let staffGroup = getgrnam("staff")
            let staffGroupID = staffGroup?.pointee.gr_gid
            
            XCTAssertNotEqual(staffGroupID, everyoneGroupID)
            
            XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path))
            XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path))
            XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path))
            XCTAssertEqual(staffGroupID, self.groupIDAtPath(validSymlinkURL.path))
            try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: ordinaryFileURL)
            try! fileManager.changeOwnerAndGroupOfItem(atRootURL: ordinaryFileURL, toMatch: ordinaryFileURL)
            try! fileManager.changeOwnerAndGroupOfItem(atRootURL: validSymlinkURL, toMatch: ordinaryFileURL)
            
            XCTAssertEqual(staffGroupID, self.groupIDAtPath(ordinaryFileURL.path))
            XCTAssertEqual(staffGroupID, self.groupIDAtPath(directoryURL.path))
            XCTAssertEqual(staffGroupID, self.groupIDAtPath(validSymlinkURL.path))
            
            XCTAssertEqual(0, chown(ordinaryFileURL.path, getuid(), everyoneGroupID!))
            XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(ordinaryFileURL.path))
            
            try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: ordinaryFileURL)
            XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path))
            
            try! fileManager.changeOwnerAndGroupOfItem(atRootURL: fileInDirectoryURL, toMatch: directoryURL)
            XCTAssertEqual(staffGroupID, self.groupIDAtPath(fileInDirectoryURL.path))
            
            try! fileManager.changeOwnerAndGroupOfItem(atRootURL: validSymlinkURL, toMatch: ordinaryFileURL)
            XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(validSymlinkURL.path))
            
            try! fileManager.changeOwnerAndGroupOfItem(atRootURL: directoryURL, toMatch: ordinaryFileURL)
            XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(directoryURL.path))
            XCTAssertEqual(everyoneGroupID, self.groupIDAtPath(fileInDirectoryURL.path))
        }
    }
    
    func testUpdateFileModificationTime()
    {
        makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
            XCTAssertNil(try? fileManager.updateModificationAndAccessTimeOfItem(at: rootURL.appendingPathComponent("does not exist")))
            
            let oldOrdinaryFileAttributes = try! FileManager.default.attributesOfItem(atPath: ordinaryFileURL.path)
            let oldDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: directoryURL.path)
            let oldValidSymlinkAttributes = try! FileManager.default.attributesOfItem(atPath: validSymlinkURL.path)
            
            sleep(1); // wait for clock to advance
            
            try! fileManager.updateModificationAndAccessTimeOfItem(at: ordinaryFileURL)
            try! fileManager.updateModificationAndAccessTimeOfItem(at: directoryURL)
            try! fileManager.updateModificationAndAccessTimeOfItem(at: validSymlinkURL)
            
            let newOrdinaryFileAttributes = try! FileManager.default.attributesOfItem(atPath: ordinaryFileURL.path)
            XCTAssertGreaterThan((newOrdinaryFileAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldOrdinaryFileAttributes[FileAttributeKey.modificationDate] as! Date), 0)
            
            let newDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: directoryURL.path)
            XCTAssertGreaterThan((newDirectoryAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldDirectoryAttributes[FileAttributeKey.modificationDate] as! Date), 0)
            
            let newSymlinkAttributes = try! FileManager.default.attributesOfItem(atPath: validSymlinkURL.path)
            XCTAssertGreaterThan((newSymlinkAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldValidSymlinkAttributes[FileAttributeKey.modificationDate] as! Date), 0)
        }
    }
    
    func testFileExists()
    {
        makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
            XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL))
            XCTAssertTrue(fileManager._itemExists(at: directoryURL))
            XCTAssertFalse(fileManager._itemExists(at: rootURL.appendingPathComponent("does not exist")))
            
            var isOrdinaryFileDirectory: ObjCBool = false
            XCTAssertTrue(fileManager._itemExists(at: ordinaryFileURL, isDirectory: &isOrdinaryFileDirectory) && !isOrdinaryFileDirectory.boolValue)
            
            var isDirectoryADirectory: ObjCBool = false
            XCTAssertTrue(fileManager._itemExists(at: directoryURL, isDirectory: &isDirectoryADirectory) && isDirectoryADirectory.boolValue)
            
            XCTAssertFalse(fileManager._itemExists(at: rootURL.appendingPathComponent("does not exist"), isDirectory: nil))
            
            XCTAssertTrue(fileManager._itemExists(at: validSymlinkURL))
            
            var validSymlinkIsADirectory: ObjCBool = false
            XCTAssertTrue(fileManager._itemExists(at: validSymlinkURL, isDirectory: &validSymlinkIsADirectory) && !validSymlinkIsADirectory.boolValue)
            
            // Symlink should still exist even if it doesn't point to a file that exists
            XCTAssertTrue(fileManager._itemExists(at: invalidSymlinkURL))
            
            var invalidSymlinkIsADirectory: ObjCBool = false
            XCTAssertTrue(fileManager._itemExists(at: invalidSymlinkURL, isDirectory: &invalidSymlinkIsADirectory) && !invalidSymlinkIsADirectory.boolValue)
        }
    }
    
    func testMakeDirectory()
    {
        makeTempFiles() { fileManager, rootURL, ordinaryFileURL, directoryURL, fileInDirectoryURL, validSymlinkURL, invalidSymlinkURL in
            XCTAssertNil(try? fileManager.makeDirectory(at: ordinaryFileURL))
            XCTAssertNil(try? fileManager.makeDirectory(at: directoryURL))
            
            XCTAssertNil(try? fileManager.makeDirectory(at: rootURL.appendingPathComponent("this should").appendingPathComponent("be a failure")))
            
            let newDirectoryURL = rootURL.appendingPathComponent("new test directory")
            XCTAssertFalse(fileManager._itemExists(at: newDirectoryURL))
            try! fileManager.makeDirectory(at: newDirectoryURL)
            
            var isDirectory: ObjCBool = false
            XCTAssertTrue(fileManager._itemExists(at: newDirectoryURL, isDirectory: &isDirectory))
            
            try! fileManager.removeItem(at: directoryURL)
            XCTAssertNil(try? fileManager.makeDirectory(at: validSymlinkURL))
        }
    }
    
    func testAcquireBadAuthorization()
    {
        let fileManager = SUFileManager.default()
        XCTAssertNil(try? fileManager._acquireAuthorization())
    }
}
 | 
	bsd-3-clause | 
| 
	penguing27/MarkdownViewer | 
	MarkdownViewer/ListViewController.swift | 
	1 | 
	6336 | 
	//
//  ListViewController.swift
//  MarkdownViewer
//
//  Created by Gen Inagaki on 2017/04/08.
//  Copyright © 2017年 Gen Inagaki. All rights reserved.
//
import UIKit
import SwiftyDropbox
class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var listActivityIndicatorView: UIActivityIndicatorView!
    
    var drb: DropboxAPI = DropboxAPI()
    var loadDataObserver: NSObjectProtocol?
    var path: String = ""
    var name: String = "Dropbox"
    let mySection = ["Folder", "File"]
    var directories: Array<Files.Metadata> = []
    var files: Array<Files.Metadata> = []
    private let refreshControl = UIRefreshControl()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        tableView.delegate = self
        tableView.dataSource = self
        
        title = self.name
        listActivityIndicatorView.hidesWhenStopped = true
        listActivityIndicatorView.startAnimating()
        self.refresh()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self.loadDataObserver!)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // Refresh
    private func refresh() {
        directories = []
        files = []
        drb.getList(path: self.path)
        
        loadDataObserver = NotificationCenter.default.addObserver(
            forName: .apiGetListComplete,
            object: nil,
            queue: nil,
            using: { notification in
                self.divideContents()
                self.tableView.reloadData()
                self.listActivityIndicatorView.stopAnimating()
                if self.tableView.refreshControl == nil {
                    self.tableView.refreshControl = self.refreshControl
                    self.refreshControl.addTarget(self, action: #selector(self.pullDownRefresh), for: .valueChanged)
                }
                self.refreshControl.endRefreshing()
            }
        )
    }
    
    // Pull down refresh
    @objc private func pullDownRefresh() {
        NotificationCenter.default.removeObserver(self.loadDataObserver!)
        self.refresh()
    }
    
    // Divide directories and files
    private func divideContents() {
        for i in 0..<drb.entries.count {
            if drb.entries[i] is Files.FileMetadata {
                self.files.append(drb.entries[i])
            } else {
                self.directories.append(drb.entries[i])
            }
        }
        files.sort { $0.name < $1.name }
        directories.sort { $0.name < $1.name }
    }
    
    // Number of sections
    func numberOfSections(in tableView: UITableView) -> Int {
        return mySection.count
    }
    
    // Sections
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return mySection[section]
    }
    
    // Number of cells
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return self.directories.count
        } else if section == 1 {
            return self.files.count
        } else {
            return 0
        }
    }
    
    // Display name to cells
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: "FileListItem") {
            if indexPath.section == 0 {
                if directories.count != 0 {
                    cell.textLabel?.text = self.directories[indexPath.row].name
                    cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
                }
            } else if indexPath.section == 1 {
                if files.count != 0 {
                    cell.textLabel?.text = self.files[indexPath.row].name
                    cell.accessoryType = UITableViewCellAccessoryType.none
                }
            }
            return cell
        }
        return UITableViewCell()
    }
    
    // Selected cell
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0 {
            // Directory
            let entry = self.directories[indexPath.row]
            let storyboard: UIStoryboard = self.storyboard!
            let selfView = storyboard.instantiateViewController(withIdentifier: "ListView") as! ListViewController
            selfView.path = entry.pathDisplay!
            selfView.name = entry.name
            self.navigationController?.pushViewController(selfView, animated: true)
        } else if indexPath.section == 1 {
            // File
            navigationItem.backBarButtonItem = UIBarButtonItem(title: "back", style: .plain, target: nil, action: nil)
            let entry = self.files[indexPath.row]
            self.performSegue(withIdentifier: "showFile", sender: entry)
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showFile" {
            let vc = segue.destination as! FileViewController
            vc.entry = sender as! Files.Metadata
        }
    }
    
    // Log out
    @IBAction func logoutDropbox(_ sender: Any) {
        let alertController = UIAlertController(title: "", message: "Do you really want to log out?", preferredStyle: .actionSheet)
        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: {(action: UIAlertAction!) -> Void in
            self.drb.logout()
            let storyboard: UIStoryboard = self.storyboard!
            let loginView = storyboard.instantiateViewController(withIdentifier: "LoginViewNavigation") as! UINavigationController
            self.present(loginView, animated: true, completion: nil)
        })
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertController.addAction(defaultAction)
        alertController.addAction(cancelAction)
        self.present(alertController, animated: true, completion: nil)
    }
}
 | 
	mit | 
| 
	charlon/scout-ios | 
	Scout/Error.swift | 
	1 | 
	884 | 
	//
//  Error.swift
//  Scout
//
//  Created by Charlon Palacay on 4/6/16.
//  Copyright © 2016 Charlon Palacay. All rights reserved.
//
struct Error {
    static let HTTPNotFoundError = Error(title: "Page Not Found", message: "There doesn’t seem to be anything here.")
    static let NetworkError = Error(title: "Can’t Connect", message: "TurbolinksDemo can’t connect to the server. Did you remember to start it?\nSee README.md for more instructions.")
    static let UnknownError = Error(title: "Unknown Error", message: "An unknown error occurred.")
    
    let title: String
    let message: String
    
    init(title: String, message: String) {
        self.title = title
        self.message = message
    }
    
    init(HTTPStatusCode: Int) {
        self.title = "Server Error"
        self.message = "The server returned an HTTP \(HTTPStatusCode) response."
    }
} | 
	apache-2.0 | 
| 
	emilstahl/swift | 
	validation-test/compiler_crashers/27523-swift-lexer-leximpl.swift | 
	9 | 
	443 | 
	// RUN: not --crash %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct B<T where g:C{struct d{
enum S<T{
class A
var f=A
enum S{
class b{
{
{{
{{{
{
{{{
{{{{{{
{
{
{([{{{{{{
{{{{{{
{{
{{
{
{
([{{
{{
{
{{
{
{
{
{
{{{
{{
{{
{{
{
{
{
{{{
{
{{{
{
{
{
{
([{{{{{{
{
{{{
{{{{{
{
{
{
{{{
{d<
 | 
	apache-2.0 | 
| 
	RocketChat/Rocket.Chat.iOS | 
	Rocket.Chat/Theme/NotThemeableViews.swift | 
	1 | 
	798 | 
	//
//  NotThemeableViews.swift
//  Rocket.Chat
//
//  Created by Samar Sunkaria on 4/29/18.
//  Copyright © 2018 Rocket.Chat. All rights reserved.
//
import UIKit
class NotThemeableView: UIView {
    override var theme: Theme? { return nil }
    override func applyTheme() { }
}
class NotThemeableTableView: UITableView {
    override var theme: Theme? { return nil }
    override func applyTheme() { }
}
class NotThemeableTableViewCell: UITableViewCell {
    override var theme: Theme? { return nil }
    override func applyTheme() { }
}
class NotThemeableNavigationBar: UINavigationBar {
    override var theme: Theme? { return nil }
    override func applyTheme() { }
}
class NotThemeableLabel: UILabel {
    override var theme: Theme? { return nil }
    override func applyTheme() { }
}
 | 
	mit | 
| 
	taketo1024/SwiftyAlgebra | 
	Sources/SwmCore/Polynomial/MultivariatePolynomial.swift | 
	1 | 
	9018 | 
	//
//  MultivariatePolynomial.swift
//  
//
//  Created by Taketo Sano on 2021/05/19.
//
public protocol MultivariatePolynomialIndeterminates: GenericPolynomialIndeterminate where Exponent == MultiIndex<NumberOfIndeterminates> {
    associatedtype NumberOfIndeterminates: SizeType
    static var isFinite: Bool { get }
    static var numberOfIndeterminates: Int { get }
    static func symbolOfIndeterminate(at i: Int) -> String
    static func degreeOfIndeterminate(at i: Int) -> Int
}
extension MultivariatePolynomialIndeterminates {
    public static var isFinite: Bool {
        NumberOfIndeterminates.isFixed
    }
    
    public static var numberOfIndeterminates: Int {
        NumberOfIndeterminates.intValue
    }
    
    public static func degreeOfIndeterminate(at i: Int) -> Int {
        1
    }
    
    public static func degreeOfMonomial(withExponent e: Exponent) -> Int {
        assert(!isFinite || Exponent.length <= numberOfIndeterminates)
        return e.indices.enumerated().sum { (i, k) in
            k * degreeOfIndeterminate(at: i)
        }
    }
    
    public static func descriptionOfMonomial(withExponent e: Exponent) -> String {
        let s = e.indices.enumerated().map{ (i, d) in
            (d != 0) ? Format.power(symbolOfIndeterminate(at: i), d) : ""
        }.joined()
        return s.isEmpty ? "1" : s
    }
}
public struct BivariatePolynomialIndeterminates<x: PolynomialIndeterminate, y: PolynomialIndeterminate>: MultivariatePolynomialIndeterminates {
    public typealias Exponent = MultiIndex<_2>
    public typealias NumberOfIndeterminates = _2
    public static func degreeOfIndeterminate(at i: Int) -> Int {
        switch i {
        case 0: return x.degree
        case 1: return y.degree
        default: fatalError()
        }
    }
    public static func symbolOfIndeterminate(at i: Int) -> String {
        switch i {
        case 0: return x.symbol
        case 1: return y.symbol
        default: fatalError()
        }
    }
}
public struct TrivariatePolynomialIndeterminates<x: PolynomialIndeterminate, y: PolynomialIndeterminate, z: PolynomialIndeterminate>: MultivariatePolynomialIndeterminates {
    public typealias Exponent = MultiIndex<_3>
    public typealias NumberOfIndeterminates = _3
    public static func degreeOfIndeterminate(at i: Int) -> Int {
        switch i {
        case 0: return x.degree
        case 1: return y.degree
        case 2: return z.degree
        default: fatalError()
        }
    }
    public static func symbolOfIndeterminate(at i: Int) -> String {
        switch i {
        case 0: return x.symbol
        case 1: return y.symbol
        case 2: return z.symbol
        default: fatalError()
        }
    }
}
public struct EnumeratedPolynomialIndeterminates<x: PolynomialIndeterminate, n: SizeType>: MultivariatePolynomialIndeterminates {
    public typealias Exponent = MultiIndex<n>
    public typealias NumberOfIndeterminates = n
    public static func degreeOfIndeterminate(at i: Int) -> Int {
        x.degree
    }
    public static func symbolOfIndeterminate(at i: Int) -> String {
        "\(x.symbol)\(Format.sub(i))"
    }
}
public protocol MultivariatePolynomialType: GenericPolynomialType where Indeterminate: MultivariatePolynomialIndeterminates {
    typealias NumberOfIndeterminates = Indeterminate.NumberOfIndeterminates
}
extension MultivariatePolynomialType {
    public static func indeterminate(_ i: Int, exponent: Int = 1) -> Self {
        let l = Indeterminate.isFinite ? Indeterminate.numberOfIndeterminates : i + 1
        let indices = (0 ..< l).map{ $0 == i ? exponent : 0 }
        let I = MultiIndex<NumberOfIndeterminates>(indices)
        return .init(elements: [I : .identity] )
    }
    
    public static var numberOfIndeterminates: Int {
        NumberOfIndeterminates.intValue
    }
    
    public static func monomial(withExponents I: [Int]) -> Self {
        monomial(withExponents: Exponent(I))
    }
    
    public static func monomial(withExponents I: Exponent) -> Self {
        .init(elements: [I: .identity])
    }
    
    public func coeff(_ exponent: Int...) -> BaseRing {
        self.coeff(Exponent(exponent))
    }
    
    public func evaluate(by values: [BaseRing]) -> BaseRing {
        assert(!Indeterminate.isFinite || values.count <= Self.numberOfIndeterminates)
        return elements.sum { (I, a) in
            a * I.indices.enumerated().multiply{ (i, e) in values.count < i ? .zero : values[i].pow(e) }
        }
    }
    
    public func evaluate(by values: BaseRing...) -> BaseRing {
        evaluate(by: values)
    }
}
// MARK: MultivariateLaurentPolynomial
public struct MultivariatePolynomial<R: Ring, xn: MultivariatePolynomialIndeterminates>: MultivariatePolynomialType {
    public typealias BaseRing = R
    public typealias Indeterminate = xn
    public let elements: [Exponent : R]
    public init(elements: [Exponent : R]) {
        assert(elements.keys.allSatisfy{ e in e.indices.allSatisfy{ $0 >= 0 } })
        self.elements = elements
    }
    
    public var inverse: Self? {
        (isConst && constCoeff.isInvertible)
            ? .init(constCoeff.inverse!)
            : nil
    }
    
    public static func monomials<S: Sequence>(ofDegree deg: Int, usingIndeterminates indices: S) -> [Self] where S.Element == Int {
        assert(indices.isUnique)
        assert(indices.allSatisfy{ $0 >= 0 })
        assert(
            deg == 0 && indices.allSatisfy{ i in Indeterminate.degreeOfIndeterminate(at: i) != 0 } ||
            deg  > 0 && indices.allSatisfy{ i in Indeterminate.degreeOfIndeterminate(at: i) >  0 } ||
            deg  < 0 && indices.allSatisfy{ i in Indeterminate.degreeOfIndeterminate(at: i) <  0 }
        )
        
        func generate(_ deg: Int, _ indices: ArraySlice<Int>) -> [[Int]] {
            if indices.isEmpty {
                return deg == 0 ? [[]] : []
            }
            
            let i = indices.last!
            let d = Indeterminate.degreeOfIndeterminate(at: i)
            let c = deg / d  // = 0 when |deg| < |d|
            
            return (0 ... c).flatMap { e -> [[Int]] in
                generate(deg - e * d, indices.dropLast()).map { res in
                    res + [e]
                }
            }
        }
        
        let exponents = generate(deg, ArraySlice(indices))
        let l = indices.max() ?? 0
        return exponents.map { list -> Self in
            let e = Array(repeating: 0, count: l + 1).with { arr in
                for (i, d) in zip(indices, list) {
                    arr[i] = d
                }
            }
            return monomial(withExponents: Exponent(e))
        }
    }
    
    public static func elementarySymmetricPolynomial<S: Sequence>(ofDegree deg: Int, usingIndeterminates indices: S) -> Self where S.Element == Int {
        assert(indices.isUnique)
        assert(indices.allSatisfy{ $0 >= 0 })
        let n = indices.count
        if deg > n {
            return .zero
        }
        
        let max = indices.max() ?? 0
        let indexer = indices.makeIndexer()
        
        let exponents = (0 ..< n).combinations(ofCount: deg).map { list -> [Int] in
            // e.g. [0, 1, 3] -> (1, 1, 0, 1)
            let set = Set(list)
            return (0 ... max).map { i in
                set.contains(indexer(i) ?? -1) ? 1 : 0
            }
        }
        
        return .init(elements: Dictionary(exponents.map{ (Exponent($0), .identity) } ))
    }
    
    public static var symbol: String {
        Indeterminate.isFinite
            ? "\(R.symbol)[\( (0 ..< numberOfIndeterminates).map{ i in Indeterminate.symbolOfIndeterminate(at: i)}.joined(separator: ", ") )]"
            : "\(R.symbol)[\( (0 ..< 3).map{ i in Indeterminate.symbolOfIndeterminate(at: i)}.joined(separator: ", ") ), …]"
    }
}
extension MultivariatePolynomial where Indeterminate.NumberOfIndeterminates: FixedSizeType {
    public static func monomials(ofDegree deg: Int) -> [Self] {
        monomials(ofDegree: deg, usingIndeterminates: 0 ..< numberOfIndeterminates)
    }
    
    public static func elementarySymmetricPolynomial(ofDegree deg: Int) -> Self {
        elementarySymmetricPolynomial(ofDegree: deg, usingIndeterminates: 0 ..< numberOfIndeterminates)
    }
}
extension MultivariatePolynomial: ExpressibleByIntegerLiteral where R: ExpressibleByIntegerLiteral {}
// MARK: MultivariateLaurentPolynomial
public struct MultivariateLaurentPolynomial<R: Ring, xn: MultivariatePolynomialIndeterminates>: MultivariatePolynomialType {
    public typealias BaseRing = R
    public typealias Indeterminate = xn
    public let elements: [Exponent : R]
    public init(elements: [Exponent : R]) {
        self.elements = elements
    }
    
    public var inverse: Self? {
        if isMonomial && leadCoeff.isInvertible {
            let d = leadExponent
            let a = leadCoeff
            return .init(elements: [-d: a.inverse!])
        } else {
            return nil
        }
    }
}
 | 
	cc0-1.0 | 
| 
	gupuru/StreetPassBLE-iOS | 
	Example/ViewController.swift | 
	1 | 
	4758 | 
	//
//  ViewController.swift
//  Example
//
//  Created by 新見晃平 on 2016/02/23.
//  Copyright © 2016年 kohei Niimi. All rights reserved.
//
import UIKit
import StreetPass
class ViewController: UIViewController, StreetPassDelegate, UITextFieldDelegate {
   
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var logTextView: UITextView!
    @IBOutlet weak var startStopUIButton: UIButton!
    
    fileprivate let street: StreetPass = StreetPass()
    fileprivate var startStopIsOn: Bool = false
    
    //MARK: - Lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // アラート表示の許可をもらう
        let setting = UIUserNotificationSettings(types: [.sound, .alert], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(setting)
        //delegateなど
        street.delegate = self
        nameTextField.delegate = self
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @IBAction func onTouchUpInsideStartStopButton(_ sender: UIButton) {
        if !startStopIsOn {
            //buttonの背景色, 文字変更
            startStopIsOn = true
            startStopUIButton.setTitle("Stop", for: UIControlState())
            startStopUIButton.backgroundColor = Color().stop()
            logTextView.text = ""
            setLogText("Start StreetPass")
            view.endEditing(true)
            //textfieldに入っている文言取得
            var sendData: String = ""
            if nameTextField.text != nil {
                sendData = nameTextField.text!
            }
            //bleの設定
            let streetPassSettings: StreetPassSettings = StreetPassSettings()
                .sendData(sendData)
                .allowDuplicates(false)
                .isConnect(true)
            //bleライブラリ開始
            street.start(streetPassSettings)
        } else {
            //buttonの背景色, 文字変更
            startStopIsOn = false
            startStopUIButton.setTitle("Start", for: UIControlState())
            startStopUIButton.backgroundColor = Color().main()
            setLogText("Stop StreetPass")
            //bleライブラリ停止
            street.stop()
        }
    }
    
    //MARK: - StreetPassDelegate
    
    func centralManagerState(_ state: CentralManagerState) {
        switch state {
        case .poweredOn:
            setLogText("Start central manager")
        default:
            setLogText("Failure central manager")
            break
        }
    }
    
    func peripheralManagerState(_ state: PeripheralManagerState) {
        switch state {
        case .poweredOn:
            setLogText("Start peripheral manager")
            break
        default:
            setLogText("Failure peripheral manager")
            break
        }
    }
    
    func advertisingState() {
        setLogText("Now, Advertising")
    }
    
    func peripheralDidAddService() {
        setLogText("Start Service")
    }
    
    func deviceConnectedState(_ connectedDeviceInfo : ConnectedDeviceInfo) {
        if let status = connectedDeviceInfo.status {
            switch status {
            case .success:
                setLogText("Success Device Connect")
            case .disConected:
                setLogText("DisConnect Device")
            case .failure:
                setLogText("Connect Failer")
            }
        }
    }
    public func streetPassError(_ error: Error) {
        setLogText("error.localizedDescription")
    }
    
    func nearByDevices(_ deveiceInfo: DeveiceInfo) {
        setLogText("Near by device: \(deveiceInfo.deviceName)")
    }
    
    func receivedData(_ receivedData: ReceivedData) {
        if let data = receivedData.data {
            setLogText("Receive Data: \(data)")
            // Notificationの生成する
            let myNotification: UILocalNotification = UILocalNotification()
            myNotification.alertBody = data
            myNotification.fireDate = Date(timeIntervalSinceNow: 1)
            myNotification.timeZone = TimeZone.current
            UIApplication.shared.scheduleLocalNotification(myNotification)
        }
    }
    
    //MARK: - UITextFieldDelegate
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool{
        // キーボード閉じる
        textField.resignFirstResponder()
        return true
    }
    
    //MARK: - Sub Methods
    
    /**
    textViewに値をいれる
    */
    fileprivate func setLogText(_ text: String) {
        DispatchQueue.main.async {
            let log: String = self.logTextView.text
            self.logTextView.text = log + text + "\n"
        }
    }
}
 | 
	mit | 
| 
	monyschuk/CwlSignal | 
	CwlSignal.playground/Pages/Parallel composition - operators.xcplaygroundpage/Contents.swift | 
	1 | 
	3416 | 
	/*:
# Parallel composition 2
> **This playground requires the CwlSignal.framework built by the CwlSignal_macOS scheme.** If you're seeing the error: "no such module 'CwlSignal'" follow the Build Instructions on the [Introduction](Introduction) page.
## Some advanced operators
There are lots of different "operator" functions for merging and combining `Signal` instances. This page demonstrates `switchLatest` and `timeout` but there are many more (including the `combineLatest` used in [App scenario - dynamic view properties](App%20scenario%20-%20dynamic%20view%20properties)).
This page contains a `Service`. The service constructs an underlying signal and times out if the underlying signal runs longer than a specified timeout time. The service is complicated by the requirement that the `connect` function can be called at any time and any previous connection must be abandoned.
The `switchLatest` function is used to abandon previous connection attempts. The `timeout` function is used to enforce the timeout. There are also other functions like `materialize` and `multicast` in use (I'll leave you to guess why).
---
 */
import CwlSignal
import Foundation
/// This is the "Service". When `connect` is called, it creates a `connect` signal (using the function provided on `init`) and runs it until it either completes or a timeout expires. Connect can be called repeatedly and any previous connection attempt will be abandoned.
class Service {
   private let input: SignalInput<DispatchTimeInterval>
   
   // Instead of "handler" callbacks, output is now via this signal
   let signal: SignalMulti<Result<String>>
	
	// The behavior of this class is is encapsulated in the signal, constructed on `init`.
   init(connect: @escaping () -> Signal<String>) {
      (self.input, self.signal) = Signal<DispatchTimeInterval>.create { s in
      	// Return results only from the latest connection attempt
			Signal<Result<String>>.switchLatest(
	      	// Convert each incoming timeout duration into a connection attempt
				s.map { interval in connect().timeout(interval: interval, resetOnValue: false).materialize() }
			).multicast()
      }
   }
   // Calling connect just sends the timeout value to the existing signal input
   func connect(seconds: Double) {
      input.send(value: .fromSeconds(seconds))
   }
}
// Create an instance of the service
let service = Service { Signal<String>.timer(interval: .fromSeconds(2), value: "Hello, world!") }
// Subscribe to the output of the service
let endpoint = service.signal.subscribe { result in
	switch result {
	case .success(.success(let message)): print("Connected with message: \(message)")
	case .success(.failure(SignalError.closed)): print("Connection closed successfully")
	case .success(.failure(SignalError.timeout)): print("Connection failed with timeout")
	default: print("Service was probably released")
	}
}
// Try to connect
service.connect(seconds: 1.0)
// Let everything run for a 10 seconds.
RunLoop.current.run(until: Date(timeIntervalSinceNow: 10.0))
// You'd normally store the endpoint in a parent and let ARC automatically control its lifetime.
endpoint.cancel()
/*:
---
*This example writes to the "Debug Area". If it is not visible, show it from the menubar: "View" → "Debug Area" → "Show Debug Area".*
[Next page: Advanced behaviors - continuous](@next)
[Previous page: Parallel composition - combine](@previous)
*/
 | 
	isc | 
| 
	rnystrom/GitHawk | 
	Classes/Search/SearchRecentSectionController.swift | 
	1 | 
	2737 | 
	//
//  SearchRecentSectionController.swift
//  Freetime
//
//  Created by Ryan Nystrom on 9/4/17.
//  Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import Foundation
import IGListKit
import SwipeCellKit
protocol SearchRecentSectionControllerDelegate: class {
    func didSelect(recentSectionController: SearchRecentSectionController, viewModel: SearchRecentViewModel)
    func didDelete(recentSectionController: SearchRecentSectionController, viewModel: SearchRecentViewModel)
}
// bridge to NSString for NSObject conformance
final class SearchRecentSectionController: ListGenericSectionController<SearchRecentViewModel>, SwipeCollectionViewCellDelegate {
    weak var delegate: SearchRecentSectionControllerDelegate?
    lazy var recentStore = SearchRecentStore()
    init(delegate: SearchRecentSectionControllerDelegate) {
        self.delegate = delegate
        super.init()
    }
    override func sizeForItem(at index: Int) -> CGSize {
        return collectionContext.cellSize(
            with: Styles.Sizes.tableCellHeight + Styles.Sizes.rowSpacing * 2
        )
    }
    override func cellForItem(at index: Int) -> UICollectionViewCell {
        guard let cell = collectionContext?.dequeueReusableCell(of: SearchRecentCell.self, for: self, at: index) as? SearchRecentCell
            else { fatalError("Missing context or wrong cell type") }
        cell.delegate = self
        cell.configure(viewModel: searchViewModel)
        return cell
    }
    override func didSelectItem(at index: Int) {
        collectionContext?.deselectItem(at: index, sectionController: self, animated: trueUnlessReduceMotionEnabled)
        delegate?.didSelect(recentSectionController: self, viewModel: searchViewModel)
    }
    // MARK: SwipeCollectionViewCellDelegate
    func collectionView(_ collectionView: UICollectionView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        guard orientation == .right else { return nil }
        let action = DeleteSwipeAction { [weak self] _, _ in
            guard let strongSelf = self, let object = strongSelf.object else { return }
            strongSelf.delegate?.didDelete(recentSectionController: strongSelf, viewModel: object)
        }
        return [action]
    }
    func collectionView(_ collectionView: UICollectionView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeTableOptions {
        var options = SwipeTableOptions()
        options.expansionStyle = .destructive
        return options
    }
    // MARK: Private API
    var searchViewModel: SearchRecentViewModel {
        return object ?? SearchRecentViewModel(query: .search(""))
    }
}
 | 
	mit | 
| 
	offfffz/PHAssetImageResizer-Bolts | 
	ImageResizer.swift | 
	1 | 
	2384 | 
	//
//  ImageResizer.swift
//
//  Created by offz on 7/21/2558 BE.
//  Copyright (c) 2558 off. All rights reserved.
//
import Bolts
import Photos
import FCFileManager
public class ImageResizer {
    
    let maxConcurrentCount: Int
    let targetFolderPath: String
    let sizeToFit: CGSize
    
    lazy var imageProcessingQueue: NSOperationQueue = {
        let queue = NSOperationQueue()
        queue.qualityOfService = NSQualityOfService.Background
        queue.maxConcurrentOperationCount = self.maxConcurrentCount
        
        return queue
    }()
    
    public init(targetFolderPath: String, sizeToFit: CGSize, maxConcurrentCount: Int = 3) {
        self.maxConcurrentCount = maxConcurrentCount
        self.targetFolderPath = targetFolderPath
        self.sizeToFit = sizeToFit
    }
    
    public func resizeAndCacheAssets(#assets: [PHAsset]) -> BFTask {
        let imgManager = PHImageManager.defaultManager()
        var tasks = [BFTask]()
        var counter = 0
        
        let imageRequestOptions = PHImageRequestOptions()
        imageRequestOptions.resizeMode = .Exact
        imageRequestOptions.synchronous = true
        
        for asset in assets {
            let fileName = "\(counter++).jpg"
            let filePath = targetFolderPath.stringByAppendingPathComponent(fileName)
            let completionSource = BFTaskCompletionSource()
            
            imageProcessingQueue.addOperation(NSBlockOperation(block: {
                imgManager.requestImageForAsset(asset, targetSize: sizeToFit, contentMode: PHImageContentMode.AspectFit, options: imageRequestOptions, resultHandler: {
                    [unowned self](image, _) -> Void in
                    
                    let imageData = UIImageJPEGRepresentation(image, 0.8)
                    if imageData != nil && FCFileManager.writeFileAtPath(filePath, content: imageData) {
                        completionSource.setResult(filePath)
                    } else {
                        completionSource.setError(NSError(domain: "ImageResizer", code: 101,
                            userInfo:[NSLocalizedDescriptionKey: "Cannot write image to \(filePath)"]))
                    }
                })
            }))
            
            tasks.append(completionSource.task)
        }
        
        return BFTask(forCompletionOfAllTasksWithResults: tasks)
    }
} | 
	mit | 
| 
	wisonlin/TimeSound | 
	TimeSound/TimeSound/TSRemindCreateViewController.swift | 
	1 | 
	2967 | 
	//
//  TSRemindCreateViewController.swift
//  TimeSound
//
//  Created by wison on 3/6/16.
//  Copyright © 2016 HomeStudio. All rights reserved.
//
import UIKit
import RealmSwift
class TSRemindCreateViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TSSoundSelectDelegate {
    // MARK: Properties
    
    @IBOutlet weak var tableView : UITableView!
    @IBOutlet weak var timePicker : UIDatePicker!
    
    var time = NSDate(timeIntervalSinceNow: 0)
    var soundChanged = false
    var selectedSound = TSSoundManger().soundList.first!
    
    // MARK: View Life Cycle
    
    override func viewWillAppear(animated: Bool) {
        if soundChanged {
            self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: .Fade)
        }
    }
    
    // MARK: - Actions
    
    @IBAction func onSave() {
        let remind = TSRemind(value: ["time" : time, "sound" : selectedSound, "enable" : true])
        let realm = try! Realm()
        try! realm.write({
            realm.add(remind)
        })
        
        self.navigationController?.popViewControllerAnimated(true)
        NSNotificationCenter.defaultCenter().postNotificationName("TSDataChanged", object: nil)
    }
    
    @IBAction func onTimePickerValueChanged() {
        time = (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! TSTimePickerCell).timePicker!.date
    }
    
    // MARK: - UITableViewDataSource
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return 216
        case 1:
            return 44
        default:
            return 0
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell : UITableViewCell!
        switch indexPath.row {
        case 0:
            cell = tableView.dequeueReusableCellWithIdentifier("TSTimePickerCell")!
        case 1:
            cell = tableView.dequeueReusableCellWithIdentifier("TSSoundCell")!
            cell.textLabel!.text = "Sound"
            cell.detailTextLabel!.text = selectedSound
        default: break
        }
        
        return cell
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        (segue.destinationViewController as! TSSoundSelectViewController).delegate = self
        let selectIndex = TSSoundManger().soundList.indexOf(selectedSound)!
        (segue.destinationViewController as! TSSoundSelectViewController).selectIndex = selectIndex
    }
    
    // MARK: - TSSoundSelectDelegate
    
    func onSelectSound(sender: AnyObject, selectedSound: String) {
        soundChanged = true
        self.selectedSound = selectedSound
    }
}
 | 
	mit | 
| 
	frootloops/swift | 
	test/SILGen/guaranteed_self.swift | 
	1 | 
	26248 | 
	// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
protocol Fooable {
  init()
  func foo(_ x: Int)
  mutating func bar()
  mutating func bas()
  var prop1: Int { get set }
  var prop2: Int { get set }
  var prop3: Int { get nonmutating set }
}
protocol Barrable: class {
  init()
  func foo(_ x: Int)
  func bar()
  func bas()
  var prop1: Int { get set }
  var prop2: Int { get set }
  var prop3: Int { get set }
}
struct S: Fooable {
  var x: C? // Make the type nontrivial, so +0/+1 is observable.
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> @owned S
  init() {}
  // TODO: Way too many redundant r/r pairs here. Should use +0 rvalues.
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed S) -> () {
  // CHECK:       bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
  // CHECK-NOT:     copy_value [[SELF]]
  // CHECK-NOT:     destroy_value [[SELF]]
  func foo(_ x: Int) {
    self.foo(x)
  }
  func foooo(_ x: (Int, Bool)) {
    self.foooo(x)
  }
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout S) -> ()
  // CHECK:       bb0([[SELF:%.*]] : @trivial $*S):
  // CHECK-NOT:     destroy_addr [[SELF]]
  mutating func bar() {
    self.bar()
  }
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed S) -> ()
  // CHECK:       bb0([[SELF:%.*]] : @guaranteed $S):
  // CHECK-NOT:     copy_value [[SELF]]
  // CHECK-NOT:     destroy_value [[SELF]]
  func bas() {
    self.bas()
  }
  var prop1: Int = 0
  // Getter for prop1
  // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sivg : $@convention(method) (@guaranteed S) -> Int
  // CHECK:       bb0([[SELF:%.*]] : @guaranteed $S):
  // CHECK-NOT:     destroy_value [[SELF]]
  // Setter for prop1
  // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sivs : $@convention(method) (Int, @inout S) -> ()
  // CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
  // CHECK-NOT:     load [[SELF_ADDR]]
  // CHECK-NOT:     destroy_addr [[SELF_ADDR]]
  // materializeForSet for prop1
  // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
  // CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
  // CHECK-NOT:     load [[SELF_ADDR]]
  // CHECK-NOT:     destroy_addr [[SELF_ADDR]]
  var prop2: Int {
    // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop2Sivg : $@convention(method) (@guaranteed S) -> Int
    // CHECK:       bb0([[SELF:%.*]] : @guaranteed $S):
    // CHECK-NOT:     destroy_value [[SELF]]
    get { return 0 }
    // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop2Sivs : $@convention(method) (Int, @inout S) -> ()
    // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop2Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
    set { }
  }
  var prop3: Int {
    // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop3Sivg : $@convention(method) (@guaranteed S) -> Int
    // CHECK:       bb0([[SELF:%.*]] : @guaranteed $S):
    // CHECK-NOT:     destroy_value [[SELF]]
    get { return 0 }
    // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop3Sivs : $@convention(method) (Int, @guaranteed S) -> ()
    // CHECK:       bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
    // CHECK-NOT:     destroy_value [[SELF]]
    // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop3Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
    // CHECK:       bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
    // CHECK-NOT:     destroy_value [[SELF]]
    nonmutating set { }
  }
}
// Witness thunk for nonmutating 'foo'
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> () {
// CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK:         [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT:     destroy_value [[SELF]]
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for mutating 'bar'
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> () {
// CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT:     load [[SELF_ADDR]]
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for 'bas', which is mutating in the protocol, but nonmutating
// in the implementation
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP3bas{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> ()
// CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK:         [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK:         end_borrow [[SELF]]
// CHECK-NOT:     destroy_value [[SELF]]
// Witness thunk for prop1 getter
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop1SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK:         [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT:     destroy_value [[SELF]]
// CHECK-NOT:     destroy_value [[SELF]]
// Witness thunk for prop1 setter
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop1SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () {
// CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for prop1 materializeForSet
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop1SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 getter
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop2SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK:         [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT:     destroy_value [[SELF]]
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 setter
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop2SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () {
// CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 materializeForSet
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop2SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 getter
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop3SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK:         [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT:     destroy_value [[SELF]]
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating setter
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop3SivsTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> ()
// CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK:         [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT:     destroy_value [[SELF]]
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating materializeForSet
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop3SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK:         [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT:     destroy_value [[SELF]]
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// CHECK:       } // end sil function '_T015guaranteed_self1SVAA7FooableA2aDP5prop3SivmTW'
//
// TODO: Expected output for the other cases
//
struct AO<T>: Fooable {
  var x: T?
  init() {}
  // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
  // CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>):
  // CHECK:         apply {{.*}} [[SELF_ADDR]]
  // CHECK-NOT:     destroy_addr [[SELF_ADDR]]
  // CHECK:       }
  func foo(_ x: Int) {
    self.foo(x)
  }
  mutating func bar() {
    self.bar()
  }
  // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (@in_guaranteed AO<T>) -> ()
  // CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>):
  // CHECK-NOT:     destroy_addr [[SELF_ADDR]]
  func bas() {
    self.bas()
  }
  var prop1: Int = 0
  var prop2: Int {
    // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop2Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int {
    // CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>):
    // CHECK-NOT:     destroy_addr [[SELF_ADDR]]
    get { return 0 }
    set { }
  }
  var prop3: Int {
    // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop3Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int
    // CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>):
    // CHECK-NOT:     destroy_addr [[SELF_ADDR]]
    get { return 0 }
    // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop3Sivs : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
    // CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>):
    // CHECK-NOT:     destroy_addr [[SELF_ADDR]]
    // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self2AOV5prop3Sivm : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed AO<T>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
    // CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>):
    // CHECK-NOT:     destroy_addr [[SELF_ADDR]]
    // CHECK:       }
    nonmutating set { }
  }
}
// Witness for nonmutating 'foo'
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self2AOVyxGAA7FooableA2aEP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (Int, @in_guaranteed AO<τ_0_0>) -> ()
// CHECK:       bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<τ_0_0>):
// CHECK:         apply {{.*}} [[SELF_ADDR]]
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
// Witness for 'bar', which is mutating in protocol but nonmutating in impl
// CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self2AOVyxGAA7FooableA2aEP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (@inout AO<τ_0_0>) -> ()
// CHECK:       bb0([[SELF_ADDR:%.*]] : @trivial $*AO<τ_0_0>):
// -- NB: This copy is not necessary, since we're willing to assume an inout
//        parameter is not mutably aliased.
// CHECK:         apply {{.*}}([[SELF_ADDR]])
// CHECK-NOT:     destroy_addr [[SELF_ADDR]]
class C: Fooable, Barrable {
  // Allocating initializer
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C
  // CHECK:         [[SELF1:%.*]] = alloc_ref $C
  // CHECK-NOT:     [[SELF1]]
  // CHECK:         [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
  // CHECK-NOT:     [[SELF2]]
  // CHECK:         return [[SELF2]]
  // Initializing constructors still have the +1 in, +1 out convention.
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C) -> @owned C {
  // CHECK:       bb0([[SELF:%.*]] : @owned $C):
  // CHECK:         [[MARKED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]]
  // CHECK:         [[MARKED_SELF_RESULT:%.*]] = copy_value [[MARKED_SELF]]
  // CHECK:         destroy_value [[MARKED_SELF]]
  // CHECK:         return [[MARKED_SELF_RESULT]]
  // CHECK:       } // end sil function '_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc'
  // @objc thunk for initializing constructor
  // CHECK-LABEL: sil hidden [thunk] @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (@owned C) -> @owned C
  // CHECK:       bb0([[SELF:%.*]] : @owned $C):
  // CHECK-NOT:     copy_value [[SELF]]
  // CHECK:         [[SELF2:%.*]] = apply {{%.*}}([[SELF]])
  // CHECK-NOT:     destroy_value [[SELF]]
  // CHECK-NOT:     destroy_value [[SELF2]]
  // CHECK:         return [[SELF2]]
  // CHECK: } // end sil function '_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo'
  @objc required init() {}
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed C) -> ()
  // CHECK:       bb0({{.*}} [[SELF:%.*]] : @guaranteed $C):
  // CHECK-NOT:     copy_value
  // CHECK-NOT:     destroy_value
  // CHECK:       } // end sil function '_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F'
  // CHECK-LABEL: sil hidden [thunk] @_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Int, C) -> () {
  // CHECK:       bb0({{.*}} [[SELF:%.*]] : @unowned $C):
  // CHECK:         [[SELF_COPY:%.*]] = copy_value [[SELF]]
  // CHECK:         [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
  // CHECK:         apply {{.*}}({{.*}}, [[BORROWED_SELF_COPY]])
  // CHECK:         end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
  // CHECK:         destroy_value [[SELF_COPY]]
  // CHECK-NOT:     destroy_value [[SELF_COPY]]
  // CHECK-NOT:     destroy_value [[SELF]]
  // CHECK:       } // end sil function '_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo'
  @objc func foo(_ x: Int) {
    self.foo(x)
  }
  @objc func bar() {
    self.bar()
  }
  @objc func bas() {
    self.bas()
  }
  // CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1CC5prop1SivgTo : $@convention(objc_method) (C) -> Int
  // CHECK:       bb0([[SELF:%.*]] : @unowned $C):
  // CHECK:         [[SELF_COPY:%.*]] = copy_value [[SELF]]
  // CHECK:         [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
  // CHECK:         apply {{.*}}([[BORROWED_SELF_COPY]])
  // CHECK:         end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
  // CHECK:         destroy_value [[SELF_COPY]]
  // CHECK-NOT:     destroy_value [[SELF]]
  // CHECK-NOT:     destroy_value [[SELF_COPY]]
  // CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1CC5prop1SivsTo : $@convention(objc_method) (Int, C) -> ()
  // CHECK:       bb0({{.*}} [[SELF:%.*]] : @unowned $C):
  // CHECK:         [[SELF_COPY:%.*]] = copy_value [[SELF]]
  // CHECK:         [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
  // CHECK:         apply {{.*}} [[BORROWED_SELF_COPY]]
  // CHECK:         end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
  // CHECK:         destroy_value [[SELF_COPY]]
  // CHECK-NOT:     destroy_value [[SELF_COPY]]
  // CHECK-NOT:     destroy_value [[SELF]]
  // CHECK:       }
  @objc var prop1: Int = 0
  @objc var prop2: Int {
    get { return 0 }
    set {}
  }
  @objc var prop3: Int {
    get { return 0 }
    set {}
  }
}
class D: C {
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1DC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick D.Type) -> @owned D
  // CHECK:         [[SELF1:%.*]] = alloc_ref $D
  // CHECK-NOT:     [[SELF1]]
  // CHECK:         [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
  // CHECK-NOT:     [[SELF1]]
  // CHECK-NOT:     [[SELF2]]
  // CHECK:         return [[SELF2]]
  // CHECK-LABEL: sil hidden @_T015guaranteed_self1DC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned D) -> @owned D
  // CHECK:       bb0([[SELF:%.*]] : @owned $D):
  // CHECK:         [[SELF_BOX:%.*]] = alloc_box ${ var D }
  // CHECK-NEXT:    [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
  // CHECK-NEXT:    [[PB:%.*]] = project_box [[MARKED_SELF_BOX]]
  // CHECK-NEXT:    store [[SELF]] to [init] [[PB]]
  // CHECK-NOT:     [[PB]]
  // CHECK:         [[SELF1:%.*]] = load [take] [[PB]]
  // CHECK-NEXT:    [[SUPER1:%.*]] = upcast [[SELF1]]
  // CHECK-NOT:     [[PB]]
  // CHECK:         [[SUPER2:%.*]] = apply {{.*}}([[SUPER1]])
  // CHECK-NEXT:    [[SELF2:%.*]] = unchecked_ref_cast [[SUPER2]]
  // CHECK-NEXT:    store [[SELF2]] to [init] [[PB]]
  // CHECK-NOT:     [[PB]]
  // CHECK-NOT:     [[SELF1]]
  // CHECK-NOT:     [[SUPER1]]
  // CHECK-NOT:     [[SELF2]]
  // CHECK-NOT:     [[SUPER2]]
  // CHECK:         [[SELF_FINAL:%.*]] = load [copy] [[PB]]
  // CHECK-NEXT:    destroy_value [[MARKED_SELF_BOX]]
  // CHECK-NEXT:    return [[SELF_FINAL]]
  required init() {
    super.init()
  }
  // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T015guaranteed_self1DC3foo{{[_0-9a-zA-Z]*}}FTD : $@convention(method) (Int, @guaranteed D) -> ()
  // CHECK:       bb0({{.*}} [[SELF:%.*]] : @guaranteed $D):
  // CHECK:         [[SELF_COPY:%.*]] = copy_value [[SELF]]
  // CHECK:         destroy_value [[SELF_COPY]]
  // CHECK-NOT:     destroy_value [[SELF_COPY]]
  // CHECK-NOT:     destroy_value [[SELF]]
  // CHECK:       }
  dynamic override func foo(_ x: Int) {
    self.foo(x)
  }
}
func S_curryThunk(_ s: S) -> ((S) -> (Int) -> ()/*, Int -> ()*/) {
  return (S.foo /*, s.foo*/)
}
func AO_curryThunk<T>(_ ao: AO<T>) -> ((AO<T>) -> (Int) -> ()/*, Int -> ()*/) {
  return (AO.foo /*, ao.foo*/)
}
// ----------------------------------------------------------------------------
// Make sure that we properly translate in_guaranteed parameters
// correctly if we are asked to.
// ----------------------------------------------------------------------------
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @_T015guaranteed_self9FakeArrayVAA8SequenceA2aDP17_constrainElement{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Sequence) (@in FakeElement, @in_guaranteed FakeArray) -> () {
// CHECK: bb0([[ARG0_PTR:%.*]] : @trivial $*FakeElement, [[ARG1_PTR:%.*]] : @trivial $*FakeArray):
// CHECK: [[ARG0:%.*]] = load [trivial] [[ARG0_PTR]]
// CHECK: function_ref (extension in guaranteed_self):guaranteed_self.SequenceDefaults._constrainElement
// CHECK: [[FUN:%.*]] = function_ref @_{{.*}}
// CHECK: apply [[FUN]]<FakeArray>([[ARG0]], [[ARG1_PTR]])
class Z {}
public struct FakeGenerator {}
public struct FakeArray {
  var z = Z()
}
public struct FakeElement {}
public protocol FakeGeneratorProtocol {
  associatedtype Element
}
extension FakeGenerator : FakeGeneratorProtocol {
  public typealias Element = FakeElement
}
public protocol SequenceDefaults {
  associatedtype Element
  associatedtype Generator : FakeGeneratorProtocol
}
extension SequenceDefaults {
  public func _constrainElement(_: FakeGenerator.Element) {}
}
public protocol Sequence : SequenceDefaults {
  func _constrainElement(_: Element)
}
extension FakeArray : Sequence {
  public typealias Element = FakeElement
  public typealias Generator = FakeGenerator
  func _containsElement(_: Element) {}
}
// -----------------------------------------------------------------------------
// Make sure that we do not emit extra copy_values when accessing let fields of
// guaranteed parameters.
// -----------------------------------------------------------------------------
class Kraken {
  func enrage() {}
}
func destroyShip(_ k: Kraken) {}
class LetFieldClass {
  let letk = Kraken()
  var vark = Kraken()
  // CHECK-LABEL: sil hidden @_T015guaranteed_self13LetFieldClassC10letkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
  // CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass):
  // CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
  // CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken
  // CHECK-NEXT: [[KRAKEN:%.*]] = load_borrow [[WRITE]]
  // CHECK-NEXT: end_access [[WRITE]] : $*Kraken
  // CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]]
  // CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]])
  // CHECK-NEXT: end_borrow [[KRAKEN]] from [[WRITE]]
  // CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
  // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken
  // CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[READ]]
  // CHECK-NEXT: end_access [[READ]] : $*Kraken
  // CHECK:      [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
  // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[BORROWED_KRAKEN]]
  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
  // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
  // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]]
  // CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
  // CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]]
  // CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
  // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken
  // CHECK-NEXT: [[KRAKEN2:%.*]] = load [copy] [[READ]]
  // CHECK-NEXT: end_access [[READ]] : $*Kraken
  // CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
  // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
  // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[READ]]
  // CHECK-NEXT: end_access [[READ]] : $*Kraken
  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
  // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
  // CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
  // CHECK-NEXT: destroy_value [[KRAKEN]]
  // CHECK-NEXT: tuple
  // CHECK-NEXT: return
  func letkMethod() {
    letk.enrage()
    let ll = letk
    destroyShip(ll)
    var lv = letk
    destroyShip(lv)
  }
  // CHECK-LABEL: sil hidden @_T015guaranteed_self13LetFieldClassC10varkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
  // CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass):
  // CHECK: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
  // CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
  // CHECK-NEXT: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
  // CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[BORROWED_KRAKEN]]
  // CHECK-NEXT: apply [[KRAKEN_METH]]([[BORROWED_KRAKEN]])
  // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]]
  // CHECK-NEXT: destroy_value [[KRAKEN]]
  // CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
  // CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
  // CHECK:      [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
  // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[BORROWED_KRAKEN]]
  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
  // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
  // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]]
  // CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
  // CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]]
  // CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
  // CHECK-NEXT: [[KRAKEN2:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
  // CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
  // CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
  // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[WRITE]]
  // CHECK-NEXT: end_access [[WRITE]] : $*Kraken
  // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> ()
  // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
  // CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
  // CHECK-NEXT: destroy_value [[KRAKEN]]
  // CHECK-NEXT: tuple
  // CHECK-NEXT: return
  func varkMethod() {
    vark.enrage()
    let vl = vark
    destroyShip(vl)
    var vv = vark
    destroyShip(vv)
  }
}
// -----------------------------------------------------------------------------
// Make sure that in all of the following cases find has only one copy_value in it.
// -----------------------------------------------------------------------------
class ClassIntTreeNode {
  let value : Int
  let left, right : ClassIntTreeNode
  init() {}
  // CHECK-LABEL: sil hidden @_T015guaranteed_self16ClassIntTreeNodeC4find{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed ClassIntTreeNode) -> @owned ClassIntTreeNode {
  // CHECK-NOT: destroy_value
  // CHECK: copy_value
  // CHECK-NOT: copy_value
  // CHECK-NOT: destroy_value
  // CHECK: return
  func find(_ v : Int) -> ClassIntTreeNode {
    if v == value { return self }
    if v < value { return left.find(v) }
    return right.find(v)
  }
}
 | 
	apache-2.0 | 
| 
	Bajocode/ExploringModerniOSArchitectures | 
	Architectures/MVPTests/Presenter/MoviePresenterTests.swift | 
	1 | 
	1388 | 
	//
//  MoviePresenterTests.swift
//  Architectures
//
//  Created by Fabijan Bajo on 03/06/2017.
//
//
import XCTest
@testable import MVP
class MoviePresenterTests: XCTestCase {
    
    
    // MARK: - Properties
    
    var presenter: ResultsViewPresenter!
    
    
    // MARK: - Configuration
    
    override func setUp() {
        super.setUp()
        // Configure presenter with view
        let resultsVC = ResultsViewController()
        let movie = Movie(title: "Foo", posterPath: "path1", movieID: 0, releaseDate: "2017-03-23", averageRating: 8.0)
        presenter = MovieResultsPresenter(view: resultsVC, testableMovies: [movie])
        
    }
    
    override func tearDown() {
        super.tearDown()
    }
    
    
    // Presenter outputs presentable instance struct
    func test_PresentableInstance_ConvertsCorrectly() {
        let presentableMovie = presenter.presentableInstance(index: 0) as! MovieResultsPresenter.PresentableInstance
        
        XCTAssertEqual(presentableMovie.title, "Foo")
        XCTAssertEqual(presentableMovie.fullSizeURL, URL(string: "https://image.tmdb.org/t/p/original/path1")!)
        XCTAssertEqual(presentableMovie.thumbnailURL, URL(string:"https://image.tmdb.org/t/p/w300/path1")!)
        XCTAssertEqual(presentableMovie.releaseDateText, "2017-03-23")
        XCTAssertEqual(presentableMovie.ratingText, "8.0")
    }
}
 | 
	mit | 
| 
	loup-studio/Swift-Commons | 
	SwiftCommons/Classes/Ui/View/BaseCollectionCell.swift | 
	1 | 
	416 | 
	//
//  BaseCollectionCell.swift
//  Smartreno Pro
//
//  Created by Lukasz on 12/07/2017.
//  Copyright © 2017 Smart Reno. All rights reserved.
//
import UIKit
open class BaseCollectionCell : UICollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: CGRect.zero)
        setup()
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError()
    }
    
    
}
 | 
	mit | 
| 
	HighBay/EasyTimer | 
	EasyTimer/ViewController.swift | 
	2 | 
	1463 | 
	//
//  ViewController.swift
//  EasyTimer
//
//  Created by Niklas Fahl on 3/2/16.
//  Copyright © 2016 High Bay. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        // EXAMPLES
        
        // Repeat but also execute once immediately
        let _ = 2.second.interval {
            print("Repeat every 2 seconds but also execute once right away.")
        }
        
        let _ = 2.second.interval { (timer: Timer) -> Void in
            print("Repeat every 2 seconds but also execute once right away.")
        }
        
        // Repeat after delay
        let timer2 = 2.second.delayedInterval { () -> Void in
            print("Repeat every 2 seconds after 2 second delay.")
        }
        timer2.stop()
        
        // Delay something
        let _ = 2.second.delay { () -> Void in
            print("2 seconds later...")
        }
        
        // Essentially equivalent to delayedInterval
        let timer = 3.minute.timer(repeats: true, delays: true) {
            print("3 minutes later...")
        }
        timer.start()
    }
    func doSomething() {
        print("Hello")
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
 | 
	bsd-3-clause | 
| 
	Burning-Man-Earth/iBurn-iOS | 
	iBurn/BRCDataImporter.swift | 
	1 | 
	2768 | 
	//
//  BRCDataImporter.swift
//  iBurn
//
//  Created by Chris Ballinger on 7/30/17.
//  Copyright © 2017 Burning Man Earth. All rights reserved.
//
import Foundation
import Mapbox
import CocoaLumberjack
extension BRCDataImporter {
    
    /** This is where Mapbox stores its tile cache */
    private static var mapTilesDirectory: URL {
        guard var cachesUrl = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first,
            let bundleId = Bundle.main.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) as? String else {
                fatalError("Could not get map tiles directory")
        }
        cachesUrl.appendPathComponent(bundleId)
        cachesUrl.appendPathComponent(".mapbox")
        return cachesUrl
    }
    
    /** Downloads offline tiles directly from official Mapbox server */
    @objc public static func downloadMapboxOfflineTiles() {
        let storage = MGLOfflineStorage.shared
        let styleURL = URL(string: kBRCMapBoxStyleURL)!
        let bounds = MGLMapView.brc_bounds
        let region =  MGLTilePyramidOfflineRegion(styleURL: styleURL, bounds: bounds, fromZoomLevel: 13, toZoomLevel: 17)
        
        storage.addPack(for: region, withContext: Data(), completionHandler: { pack, error in
            if let pack = pack {
                pack.resume()
            } else if let error = error {
                DDLogError("Error downloading tiles: \(error)")
            }
        })
    }
    
    /** Copies the bundled Mapbox "offline" tiles to where Mapbox expects them */
    @objc public static func copyBundledTilesIfNeeded() {
        var tilesUrl = mapTilesDirectory
        if FileManager.default.fileExists(atPath: tilesUrl.path) {
            DDLogVerbose("Tiles already exist at path \(tilesUrl.path)")
            // Tiles already exist
            return
        }
        let bundle = Bundle.brc_tilesCache
        DDLogInfo("Cached tiles not found, copying from bundle... \(bundle.bundleURL) ==> \(tilesUrl)")
        do {
            let parentDir = tilesUrl.deletingLastPathComponent()
            try FileManager.default.createDirectory(at: parentDir, withIntermediateDirectories: true, attributes: nil)
            try FileManager.default.copyItem(atPath: bundle.bundlePath, toPath: tilesUrl.path)
            var resourceValues = URLResourceValues()
            resourceValues.isExcludedFromBackup = true
            try tilesUrl.setResourceValues(resourceValues)
        } catch let error {
            DDLogError("Error copying bundled tiles: \(error)")
        }
    }
    
    /** Downloads offline tiles from iBurn server */
    public static func downloadOfflineTiles() {
        // TODO: download our own offline tiles
        
    }
}
 | 
	mpl-2.0 | 
| 
	markusschlegel/DejaTextView | 
	DejaTextView.swift | 
	1 | 
	45921 | 
	//
//  DejaTextView.swift
//  DejaTextView
//
//  Created by Markus Schlegel on 17/05/15.
//  Copyright (c) 2015 Markus Schlegel. All rights reserved.
//
import UIKit
let animation_duration: Double = 0.2
let animation_spring_damping: CGFloat = 0.8
let grabber_frame: CGRect = CGRectMake(0, 0, 88, 43)
let selection_alpha: CGFloat = 0.4
let caret_tap_radius: CGFloat = 20.0
let repositioning_timer_duration: Double = 1.0
let start_grabber_y_offset: CGFloat = 20.0              // while dragging, the start grabber will be vertically positioned at this offset (0 is top edge)
let end_grabber_y_offset: CGFloat = 23.0                // while dragging, the end grabber will be vertically positioned at this offset (0 is top edge)
let start_grabber_tip_selection_offset: CGFloat = 10.0  // while dragging, the selection start will be set to the tip position + this offset
let end_grabber_tip_selection_offset: CGFloat = 10.0    // while dragging, the selection end will be set to the tip position - this offset
/// A UITextView subclass with improved text selection and cursor movement tools
public class DejaTextView: UITextView
{
    private enum DejaTextGrabberTipDirection
    {
        case Down
        case Up
    }
    
    
    
    private enum DejaTextGrabberTipAlignment
    {
        case Left
        case Right
        case Center
    }
    
    
    
    private struct CurvyPath {
        let startPoint: (CGFloat, CGFloat)
        let curves: [((CGFloat, CGFloat), (CGFloat, CGFloat), (CGFloat, CGFloat))]
        
        func toBezierPath() -> UIBezierPath {
            let path = UIBezierPath()
            path.moveToPoint(CGPointMake(self.startPoint.0, self.startPoint.1))
            
            for ((x, y), (cp1x, cp1y), (cp2x, cp2y)) in self.curves {
                path.addCurveToPoint(CGPointMake(x, y), controlPoint1: CGPointMake(cp1x, cp1y), controlPoint2: CGPointMake(cp2x, cp2y))
            }
            
            return path
        }
        
        func toBezierPath() -> CGPathRef {
            return self.toBezierPath().CGPath
        }
    }
    
    
    
    private struct LineyPath {
        let startPoint: (CGFloat, CGFloat)
        let linePoints: [(CGFloat, CGFloat)]
        
        func toBezierPath() -> UIBezierPath {
            let path = UIBezierPath()
            path.moveToPoint(CGPointMake(self.startPoint.0, self.startPoint.1))
            
            for (x, y) in self.linePoints {
                path.addLineToPoint(CGPointMake(x, y))
            }
            
            return path
        }
        
        func toBezierPath() -> CGPathRef {
            return self.toBezierPath().CGPath
        }
    }
    
    
    
    private class DejaTextGrabber: UIView
    {
        let tipDirection: DejaTextGrabberTipDirection
        var tipPosition = CGPointZero
        var extended = true
        var forcedTipAlignment: DejaTextGrabberTipAlignment? = nil
        
        private let _body = CAShapeLayer()
        private let _leftTriangle = CAShapeLayer()
        private let _rightTriangle = CAShapeLayer()
        private let _separator = CAShapeLayer()
        
        
        
        func transform(animated animated: Bool) {
            var newOrigin = self.tipPosition
            
            if let superView = self.superview {
                let xtreshold = self.frame.size.width / 2.0
                var newPaths: (CGPath, CGPathRef?, CGPathRef?, CGPathRef?)
                let alignment: DejaTextGrabberTipAlignment
                
                if self.forcedTipAlignment != nil {
                    alignment = self.forcedTipAlignment!
                } else {
                    if self.tipPosition.x < xtreshold {
                        alignment = .Left
                    } else if self.tipPosition.x > superView.frame.size.width - xtreshold {
                        alignment = .Right
                    } else {
                        alignment = .Center
                    }
                }
                
                if alignment == .Left {
                    newOrigin.x -= 14.0
                } else if alignment == .Right {
                    newOrigin.x -= 74.0
                } else {
                    newOrigin.x -= 44.0
                }
                
                
                newPaths = self.paths(tipDirection: self.tipDirection, tipAlignment: alignment, extended: self.extended)
                
                if self.tipDirection == .Down {
                    newOrigin.y -= 43.0
                }
                
                
                // Morph animation
                _body.removeAllAnimations()
                let morphAnimation = CABasicAnimation(keyPath: "path")
                morphAnimation.duration = animation_duration
                morphAnimation.fromValue = _body.presentationLayer()!.path
                morphAnimation.toValue = newPaths.0
                
                _body.path = newPaths.0
                if animated {
                    _body.addAnimation(morphAnimation, forKey: "morph")
                }
                
                
                // Fade animation
                let fadeAnimation = CABasicAnimation(keyPath: "opacity")
                fadeAnimation.duration = animation_duration
                fadeAnimation.fromValue = _leftTriangle.presentationLayer()!.opacity
                if let left = newPaths.1, right = newPaths.2, separator = newPaths.3 {
                    fadeAnimation.toValue = 1.0
                    
                    CATransaction.begin()
                    CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
                    _leftTriangle.opacity = 1.0
                    _rightTriangle.opacity = 1.0
                    _separator.opacity = 1.0
                    CATransaction.commit()
                    
                    _leftTriangle.path = left
                    _rightTriangle.path = right
                    _separator.path = separator
                } else {
                    fadeAnimation.toValue = 0.0
                    
                    CATransaction.begin()
                    CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
                    _leftTriangle.opacity = 0.0
                    _rightTriangle.opacity = 0.0
                    _separator.opacity = 0.0
                    CATransaction.commit()
                }
                
                if animated && _leftTriangle.animationForKey("fade") == nil && fadeAnimation.fromValue !== fadeAnimation.toValue {
                    _leftTriangle.addAnimation(fadeAnimation, forKey: "fade");
                }
                
                if animated && _rightTriangle.animationForKey("fade") == nil && fadeAnimation.fromValue !== fadeAnimation.toValue {
                    _rightTriangle.addAnimation(fadeAnimation, forKey: "fade");
                }
                
                if animated && _separator.animationForKey("fade") == nil && fadeAnimation.fromValue !== fadeAnimation.toValue {
                    _separator.addAnimation(fadeAnimation, forKey: "fade");
                }
                
                
                // Frame (position) animation
                let a: (Void) -> Void = {
                    var newFrame = self.frame
                    newFrame.origin = newOrigin
                    self.frame = newFrame
                }
                
                if animated {
                    UIView.animateWithDuration(animation_duration, delay: 0.0, usingSpringWithDamping: animation_spring_damping, initialSpringVelocity: 0.0, options: [], animations: a, completion: nil)
                } else {
                    a()
                }
            }
        }
        
        
        
        init(frame: CGRect, tipDirection: DejaTextGrabberTipDirection) {
            self.tipDirection = tipDirection
            super.init(frame: frame)
            
            _body.frame = grabber_frame
            _body.fillColor = UIColor.blackColor().CGColor
            _body.path = self.paths(tipDirection: self.tipDirection, tipAlignment: .Center, extended: true).0
            
            _leftTriangle.frame = grabber_frame
            _leftTriangle.fillColor = UIColor.whiteColor().CGColor
            _leftTriangle.path = self.paths(tipDirection: self.tipDirection, tipAlignment: .Center, extended: true).1
            
            _rightTriangle.frame = grabber_frame
            _rightTriangle.fillColor = UIColor.whiteColor().CGColor
            _rightTriangle.path = self.paths(tipDirection: self.tipDirection, tipAlignment: .Center, extended: true).2
            
            _separator.frame = grabber_frame
            _separator.fillColor = UIColor.whiteColor().CGColor
            _separator.path = self.paths(tipDirection: self.tipDirection, tipAlignment: .Center, extended: true).3
            
            self.layer.addSublayer(_body)
            self.layer.addSublayer(_leftTriangle)
            self.layer.addSublayer(_rightTriangle)
            self.layer.addSublayer(_separator)
        }
        
        
        
        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        
        
        override func intrinsicContentSize() -> CGSize {
            return grabber_frame.size
        }
        
        
        
        override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
            if self.extended {
                return CGRectContainsPoint(self.bounds, point)
            } else {
                return CGPathContainsPoint(_body.path, nil, point, false)
            }
        }
        
        
        
        func paths(tipDirection tipDirection: DejaTextGrabberTipDirection, tipAlignment: DejaTextGrabberTipAlignment, extended: Bool) -> (CGPath, CGPath?, CGPath?, CGPath?) {
            if extended {
                return self.extendedPaths(tipDirection: tipDirection, tipAlignment: tipAlignment)
            } else {
                return self.unextendedPaths(tipDirection: tipDirection, tipAlignment: tipAlignment)
            }
        }
        
        
        
        func extendedPaths(tipDirection tipDirection: DejaTextGrabberTipDirection, tipAlignment: DejaTextGrabberTipAlignment) -> (CGPath, CGPath?, CGPath?, CGPath?) {
            let l, r, c : LineyPath
            
            if tipDirection == .Up {
                l = LineyPath(startPoint: (18, 26), linePoints: [
                    (25, 19),
                    (25, 33),
                    (18, 26),
                    ])
                
                r = LineyPath(startPoint: (69, 26), linePoints: [
                    (62, 33),
                    (62, 19),
                    (69, 26),
                    ])
                
                c = LineyPath(startPoint: (43.5, 0), linePoints: [
                    (44.5, 0),
                    (44.5, 43),
                    (43.5, 43),
                    (43.5, 0),
                    ])
            } else {
                l = LineyPath(startPoint: (18, 26-9), linePoints: [
                    (25, 19-9),
                    (25, 33-9),
                    (18, 26-9),
                    ])
                
                r = LineyPath(startPoint: (69, 26-9), linePoints: [
                    (62, 33-9),
                    (62, 19-9),
                    (69, 26-9),
                    ])
                
                c = LineyPath(startPoint: (43.5, 0), linePoints: [
                    (44.5, 0),
                    (44.5, 43),
                    (43.5, 43),
                    (43.5, 0),
                    ])
            }
            
            let left: CGPathRef = l.toBezierPath()
            let right: CGPathRef = r.toBezierPath()
            let separator: CGPathRef = c.toBezierPath()
            
            if tipDirection == .Up && tipAlignment == .Left {
                return (self.extendedTipUpLeftPaths(), left, right, separator)
            } else if tipDirection == .Up && tipAlignment == .Right {
                return (self.extendedTipUpRightPaths(), left, right, separator)
            } else if tipDirection == .Up && tipAlignment == .Center {
                return (self.extendedTipUpPaths(), left, right, separator)
            } else if tipDirection == .Down && tipAlignment == .Left {
                return (self.extendedTipDownLeftPaths(), left, right, separator)
            } else if tipDirection == .Down && tipAlignment == .Right {
                return (self.extendedTipDownRightPaths(), left, right, separator)
            } else {
                return (self.extendedTipDownPaths(), left, right, separator)
            }
        }
        
        
        
        func unextendedPaths(tipDirection tipDirection: DejaTextGrabberTipDirection, tipAlignment: DejaTextGrabberTipAlignment) -> (CGPath, CGPath?, CGPath?, CGPath?) {
            if tipDirection == .Up && tipAlignment == .Left {
                return (self.unextendedTipUpLeftPaths(), nil, nil, nil)
            } else if tipDirection == .Up && tipAlignment == .Right {
                return (self.unextendedTipUpRightPaths(), nil, nil, nil)
            } else if tipDirection == .Up && tipAlignment == .Center {
                return (self.unextendedTipUpPaths(), nil, nil, nil)
            } else if tipDirection == .Down && tipAlignment == .Left {
                return (self.unextendedTipDownLeftPaths(), nil, nil, nil)
            } else if tipDirection == .Down && tipAlignment == .Right {
                return (self.unextendedTipDownRightPaths(), nil, nil, nil)
            } else {
                return (self.unextendedTipDownPaths(), nil, nil, nil)
            }
        }
        
        
        
        func extendedTipUpPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (44, 0), curves: [
                ((53, 9), (44, 0), (53, 9)),
                ((72, 9), (53, 9), (72, 9)),
                ((88, 26), (81, 9), (88, 17)),
                ((72, 43), (88, 35), (81, 43)),
                ((16, 43), (72, 43), (16, 43)),
                ((0, 26), (7, 43), (0, 35)),
                ((16, 9), (0, 17), (7, 9)),
                ((35, 9), (16, 9), (35, 9)),
                ((44, 0), (35, 9), (44, 0)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func extendedTipUpLeftPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (14, 0), curves: [
                ((22, 9), (16, 2), (14, 9)),
                ((72, 9), (22, 9), (72, 9)),
                ((88, 26), (81, 9), (88, 17)),
                ((72, 43), (88, 35), (81, 43)),
                ((16, 43), (72, 43), (16, 43)),
                ((0, 26), (7, 43), (0, 35)),
                ((14, 0), (0, 17), (3, 10)),
                ((14, 0), (14, 0), (14, 0)),
                ((14, 0), (14, 0), (14, 0)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func extendedTipUpRightPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (74, 0), curves: [
                ((74, 0), (74, 0), (74, 0)),
                ((74, 0), (74, 0), (74, 0)),
                ((88, 26), (85, 10), (88, 17)),
                ((72, 43), (88, 35), (81, 43)),
                ((16, 43), (72, 43), (16, 43)),
                ((0, 26), (7, 43), (0, 35)),
                ((16, 9), (0, 17), (7, 9)),
                ((66, 9), (16, 9), (66, 9)),
                ((74, 0), (74, 9), (72, 2)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func unextendedTipUpPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (44, 0), curves: [
                ((47, 5), (44, 0), (46, 3)),
                ((47, 5), (47, 5), (47, 5)),
                ((52, 15), (48, 7), (52, 10)),
                ((44, 23), (52, 20), (48, 23)),
                ((44, 23), (44, 23), (44, 23)),
                ((36, 15), (40, 23), (36, 20)),
                ((41, 5), (36, 10), (40, 7)),
                ((41, 5), (41, 5), (41, 5)),
                ((44, 0), (42, 3), (44, 0)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func unextendedTipUpLeftPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (14, 0), curves: [
                ((17, 5), (14, 0), (16, 3)),
                ((17, 5), (17, 5), (17, 5)),
                ((22, 15), (18, 7), (22, 10)),
                ((14, 23), (22, 20), (18, 23)),
                ((14, 23), (14, 23), (14, 23)),
                ((6, 15), (10, 23), (6, 20)),
                ((11, 5), (6, 10), (10, 7)),
                ((11, 5), (11, 5), (11, 5)),
                ((14, 0), (12, 3), (14, 0)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func unextendedTipUpRightPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (74, 0), curves: [
                ((77, 5), (74, 0), (76, 3)),
                ((77, 5), (77, 5), (77, 5)),
                ((82, 15), (78, 7), (82, 10)),
                ((74, 23), (82, 20), (78, 23)),
                ((74, 23), (74, 23), (74, 23)),
                ((66, 15), (70, 23), (66, 20)),
                ((71, 5), (66, 10), (70, 7)),
                ((71, 5), (71, 5), (71, 5)),
                ((74, 0), (72, 3), (74, 0)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func extendedTipDownPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (44, 43), curves: [
                ((53, 34), (44, 43), (53, 34)),
                ((72, 34), (53, 34), (72, 34)),
                ((88, 17), (81, 34), (88, 26)),
                ((72, 0), (88, 8), (81, 0)),
                ((16, 0), (72, 0), (16, 0)),
                ((0, 17), (7, 0), (0, 8)),
                ((16, 34), (0, 26), (7, 34)),
                ((35, 34), (16, 34), (35, 34)),
                ((44, 43), (35, 34), (44, 43)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func extendedTipDownLeftPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (14, 43), curves: [
                ((22, 34), (16, 41), (14, 34)),
                ((72, 34), (22, 34), (72, 34)),
                ((88, 17), (81, 34), (88, 26)),
                ((72, 0), (88, 8), (81, 0)),
                ((16, 0), (72, 0), (16, 0)),
                ((0, 17), (7, 0), (0, 8)),
                ((14, 43), (0, 26), (3, 33)),
                ((14, 43), (14, 43), (14, 43)),
                ((14, 43), (14, 43), (14, 43)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func extendedTipDownRightPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (74, 43), curves: [
                ((66, 34), (72, 41), (74, 34)),
                ((16, 34), (66, 34), (16, 34)),
                ((0, 17), (7, 34), (0, 26)),
                ((16, 0), (0, 8), (7, 0)),
                ((72, 0), (16, 0), (72, 0)),
                ((88, 17), (81, 0), (88, 8)),
                ((74, 43), (88, 26), (85, 33)),
                ((74, 43), (74, 43), (74, 43)),
                ((74, 43), (74, 43), (74, 43)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func unextendedTipDownPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (44, 43), curves: [
                ((47, 38), (44, 43), (46, 40)),
                ((47, 38), (47, 38), (47, 38)),
                ((52, 28), (48, 36), (52, 33)),
                ((44, 413), (52, 410), (48, 413)),
                ((44, 413), (44, 413), (44, 413)),
                ((36, 28), (40, 413), (36, 410)),
                ((41, 38), (36, 33), (40, 36)),
                ((41, 38), (41, 38), (41, 38)),
                ((44, 43), (42, 43-3), (44, 43)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func unextendedTipDownLeftPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (14, 43), curves: [
                ((17, 38), (14, 43), (16, 40)),
                ((17, 38), (17, 38), (17, 38)),
                ((22, 28), (18, 36), (22, 33)),
                ((14, 413), (22, 410), (18, 413)),
                ((14, 413), (14, 413), (14, 413)),
                ((6, 28), (10, 413), (6, 410)),
                ((11, 38), (6, 33), (10, 36)),
                ((11, 38), (11, 38), (11, 38)),
                ((14, 43), (12, 40), (14, 43)),
                ])
            
            return b.toBezierPath()
        }
        
        
        
        func unextendedTipDownRightPaths() -> CGPathRef {
            let b = CurvyPath(startPoint: (74, 43), curves: [
                ((77, 38), (74, 43), (76, 40)),
                ((77, 38), (77, 38), (77, 38)),
                ((82, 28), (78, 36), (82, 33)),
                ((74, 413), (82, 410), (78, 413)),
                ((74, 413), (74, 413), (74, 413)),
                ((66, 28), (70, 413), (66, 410)),
                ((71, 38), (66, 33), (70, 36)),
                ((71, 38), (71, 38), (71, 38)),
                ((74, 43), (72, 43-3), (74, 43)),
                ])
            
            return b.toBezierPath()
        }
    }
    
    
    
    
    
    
    
    // MARK: - Properties
    
    private let _startGrabber = DejaTextGrabber(frame: grabber_frame, tipDirection: .Down)
    private let _endGrabber = DejaTextGrabber(frame: grabber_frame, tipDirection: .Up)
    
    private var _selectionLayers = [CALayer]()
    
    lazy private var _singleTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "singleTapped:")
    lazy private var _doubleTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "doubleTapped:")
    lazy private var _tripleTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tripleTapped:")
    lazy private var _startGrabberTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "startGrabberTapped:")
    lazy private var _endGrabberTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "endGrabberTapped:")
    lazy private var _startGrabberPanRecognizer: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: "startGrabberPanned:")
    lazy private var _endGrabberPanRecognizer: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: "endGrabberPanned:")
    
    private var _keyboardFrame = CGRectZero
    
    private var _startGrabberIsBeingManipulated = false
    private var _endGrabberIsBeingManipulated = false
    
    private var _startGrabberRepositioningTimer: NSTimer?
    private var _endGrabberRepositioningTimer: NSTimer?
    
    private var _panOffset = CGPointZero
    
    
    
    
    
    
    
    // MARK: - Initialization
    
    public override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        self.configure()
    }
    
    
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.configure()
    }
    
    
    
    private func configure() -> Void {
        self.addSubview(_startGrabber)
        self.addSubview(_endGrabber)
        
        _singleTapRecognizer.numberOfTapsRequired = 1
        _singleTapRecognizer.requireGestureRecognizerToFail(_startGrabberTapRecognizer)
        _singleTapRecognizer.requireGestureRecognizerToFail(_endGrabberTapRecognizer)
        super.addGestureRecognizer(_singleTapRecognizer)
        
        _doubleTapRecognizer.numberOfTapsRequired = 2
        _doubleTapRecognizer.requireGestureRecognizerToFail(_startGrabberTapRecognizer)
        _doubleTapRecognizer.requireGestureRecognizerToFail(_endGrabberTapRecognizer)
        super.addGestureRecognizer(_doubleTapRecognizer)
        
        _tripleTapRecognizer.numberOfTapsRequired = 3
        _tripleTapRecognizer.requireGestureRecognizerToFail(_startGrabberTapRecognizer)
        _tripleTapRecognizer.requireGestureRecognizerToFail(_endGrabberTapRecognizer)
        super.addGestureRecognizer(_tripleTapRecognizer)
        
        _startGrabber.addGestureRecognizer(_startGrabberTapRecognizer)
        _endGrabber.addGestureRecognizer(_endGrabberTapRecognizer)
        
        _startGrabber.addGestureRecognizer(_startGrabberPanRecognizer)
        _endGrabber.addGestureRecognizer(_endGrabberPanRecognizer)
        
        _startGrabber.hidden = true
        _endGrabber.hidden = true
        
        _keyboardFrame = CGRectMake(0, UIScreen.mainScreen().bounds.height, UIScreen.mainScreen().bounds.width, 1.0)
        
        NSNotificationCenter.defaultCenter().addObserverForName(UITextViewTextDidChangeNotification, object: self, queue: NSOperationQueue.mainQueue()) {
            (notification) in
            self.selectedTextRangeDidChange()
            
            self._endGrabber.extended = false
            self._endGrabber.transform(animated: false)
        }
        
        NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: NSOperationQueue.mainQueue()) {
            (notification) in
            if let info = notification.userInfo {
                if let frame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
                    self._keyboardFrame = frame
                }
            }
        }
    }
    
    
    
    
    
    
    
    // MARK: - Misc
    
    private func selectedTextRangeDidChange() {
        for l in _selectionLayers {
            l.removeFromSuperlayer()
        }
        _selectionLayers.removeAll(keepCapacity: true)
        
        if let range = self.selectedTextRange {
            if range.empty {
                let r = self.caretRectForPosition(range.start)
                if !_endGrabberIsBeingManipulated {
                    _endGrabber.tipPosition = CGPointMake(r.origin.x + 0.5 * r.size.width, r.origin.y + r.size.height)
                    _endGrabber.transform(animated: false)
                }
                
                _startGrabber.hidden = true
                _endGrabber.hidden = false
            } else {
                let rects: [UITextSelectionRect] = super.selectionRectsForRange(range) as! [UITextSelectionRect]
                for r in rects {
                    let l = CALayer()
                    l.frame = r.rect
                    l.backgroundColor = self.tintColor.colorWithAlphaComponent(selection_alpha).CGColor
                    _selectionLayers += [l]
                    self.layer.insertSublayer(l, atIndex: 0)
                }
                
                let (topLeft, bottomRight) = self.selectionCorners()
                
                if !_startGrabberIsBeingManipulated {
                    _startGrabber.tipPosition = topLeft
                    _startGrabber.transform(animated: false)
                }
                
                if !_endGrabberIsBeingManipulated {
                    _endGrabber.tipPosition = bottomRight
                    _endGrabber.transform(animated: false)
                }
                
                _startGrabber.hidden = false
                _endGrabber.hidden = false
            }
        }
    }
    
    
    
    
    
    
    
    // MARK: - Overrides
    
    override public var selectedTextRange: UITextRange? {
        didSet {
            self.selectedTextRangeDidChange()
        }
    }
    
    
    
    override public func addGestureRecognizer(gestureRecognizer: UIGestureRecognizer) {
        // Only allow native scrolling
        if gestureRecognizer == self.panGestureRecognizer {
            super.addGestureRecognizer(gestureRecognizer)
        }
    }
    
    
    
    
    
    
    
    
    // MARK: - Public methods
    
    /**
        Use this method to add your own gesture recognizers.
    
        - parameter gestureRecognizer: An object whose class descends from the UIGestureRecognizer class.
    */
    internal func addGestureRecognizerForReal(gestureRecognizer: UIGestureRecognizer) {
        super.addGestureRecognizer(gestureRecognizer)
    }
    
    
    
    
    
    
    
    // MARK: - Action methods
    
    @objc private func singleTapped(recognizer: UITapGestureRecognizer) {
        if !self.isFirstResponder() {
            self.becomeFirstResponder()
        }
        
        let location = recognizer.locationInView(self)
        let closest = self.closestPositionToPoint(location)!
        
        
        // Check whether the tap happened in the vicinity of the caret
        if self.selectedRange.length == 0 {
            let caretRect = self.caretRectForPosition(self.selectedTextRange!.start)
            let d = distanceFrom(point: location, toRect: caretRect)
            
            if d <= caret_tap_radius {
                self.showEditingMenu()
                
                _endGrabber.extended = true
                _endGrabber.transform(animated: true)
                
                return
            }
        }
        
        
        // Tap inside or outside of words
        if self.tokenizer.isPosition(self.closestPositionToPoint(location)!, withinTextUnit: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue) && self.tokenizer.isPosition(self.closestPositionToPoint(location)!, withinTextUnit: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue) {
            var rightLeft = self.tokenizer.positionFromPosition(closest, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue)!
            rightLeft = self.tokenizer.positionFromPosition(rightLeft, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue)!
            let rightLeftRect = self.caretRectForPosition(rightLeft)
            
            var leftRight = self.tokenizer.positionFromPosition(closest, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue)!
            leftRight = self.tokenizer.positionFromPosition(leftRight, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue)!
            let leftRightRect = self.caretRectForPosition(leftRight)
            
            if distanceFrom(point: location, toRect: rightLeftRect) < distanceFrom(point: location, toRect: leftRightRect) {
                self.selectedTextRange = self.textRangeFromPosition(rightLeft, toPosition: rightLeft)
            } else {
                self.selectedTextRange = self.textRangeFromPosition(leftRight, toPosition: leftRight)
            }
        } else {
            self.selectedTextRange = self.textRangeFromPosition(closest, toPosition: closest)
        }
        
        self.hideEditingMenu()
        
        _endGrabber.extended = false
        _endGrabber.transform(animated: false)
    }
    
    
    
    @objc private func doubleTapped(recognizer: UITapGestureRecognizer) {
        if !self.isFirstResponder() {
            self.becomeFirstResponder()
        }
        
        let location = recognizer.locationInView(self)
        let closest = self.closestPositionToPoint(location)!
        
        var range = self.tokenizer.rangeEnclosingPosition(closest, withGranularity: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue)
        
        if range == nil {
            range = self.tokenizer.rangeEnclosingPosition(closest, withGranularity: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue)
        }
        
        if range != nil {
            self.selectedTextRange = range;
        } else {
            var right: UITextPosition?
            var rightRight: UITextPosition?
            var left: UITextPosition?
            var leftLeft: UITextPosition?
            
            right = self.tokenizer.positionFromPosition(closest, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue)
            if right != nil {
                rightRight = self.tokenizer.positionFromPosition(right!, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue)
            }
            left = self.tokenizer.positionFromPosition(closest, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue)
            if left != nil {
                leftLeft = self.tokenizer.positionFromPosition(left!, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue)
            }
            
            let rightRect = self.caretRectForPosition(right!)
            let leftRect = self.caretRectForPosition(left!)
            
            if distanceFrom(point: location, toRect: rightRect) < distanceFrom(point: location, toRect: leftRect) {
                self.selectedTextRange = self.textRangeFromPosition(right!, toPosition: rightRight!)
            } else {
                self.selectedTextRange = self.textRangeFromPosition(left!, toPosition: leftLeft!)
            }
        }
        
        _startGrabber.extended = true
        _startGrabber.transform(animated: false)
        _endGrabber.extended = true
        _endGrabber.transform(animated: false)
        
        self.showEditingMenu()
    }
    
    
    
    @objc private func tripleTapped(recognizer: UITapGestureRecognizer) {
        if !self.isFirstResponder() {
            self.becomeFirstResponder()
        }
        
        let range = self.textRangeFromPosition(self.beginningOfDocument, toPosition: self.endOfDocument)
        self.selectedTextRange = range
        
        _startGrabber.extended = true
        _startGrabber.transform(animated: false)
        _endGrabber.extended = true
        _endGrabber.transform(animated: false)
        
        self.showEditingMenu()
    }
    
    
    
    @objc private func startGrabberTapped(recognizer: UITapGestureRecognizer) {
        if !_startGrabber.extended {
            self.showEditingMenu()
            
            _startGrabber.extended = true
            _startGrabber.transform(animated: true)
            return
        }
        
        _startGrabberIsBeingManipulated = true
        
        
        // Set the timer
        _startGrabberRepositioningTimer?.invalidate()
        _startGrabberRepositioningTimer = NSTimer.scheduledTimerWithTimeInterval(repositioning_timer_duration, target: self, selector: "startGrabberRepositioningTimerFired:", userInfo: nil, repeats: false)
        
        
        // Set text range according to the button that has been tapped
        var pos = self.selectedRange.location
        var len = self.selectedRange.length
        
        let location = recognizer.locationInView(_startGrabber)
        
        if location.x <= _startGrabber.bounds.size.width / 2.0 {
            if pos != 0 {
                pos--
                len++
            }
        } else {
            if len != 1 {
                pos++
                len--
            }
        }
        
        self.selectedTextRange = self.textRangeFromPosition(self.positionFromPosition(self.beginningOfDocument, offset: pos)!, toPosition: self.positionFromPosition(self.beginningOfDocument, offset: pos + len)!)
        
        
        // Show editing menu
        self.showEditingMenu()
    }
    
    
    
    @objc private func endGrabberTapped(recognizer: UITapGestureRecognizer) {
        if !_endGrabber.extended {
            self.showEditingMenu()
            
            _endGrabber.extended = true
            _endGrabber.transform(animated: true)
            return
        }
        
        _endGrabberIsBeingManipulated = true
        
        
        // Set the timer
        _endGrabberRepositioningTimer?.invalidate()
        _endGrabberRepositioningTimer = NSTimer.scheduledTimerWithTimeInterval(repositioning_timer_duration, target: self, selector: "endGrabberRepositioningTimerFired:", userInfo: nil, repeats: false)
        
        
        // Set text range according to the button that has been tapped
        var pos = self.selectedRange.location
        var len = self.selectedRange.length
        
        let location = recognizer.locationInView(_endGrabber)
        
        if location.x <= _endGrabber.bounds.size.width / 2.0 {
            if len > 0 {
                if len != 1 {
                    len--
                }
            } else {
                if pos != 0 {
                    pos--
                }
            }
        } else {
            if len > 0 {
                if self.text.characters.count != pos + len {
                    len++
                }
            } else {
                if self.text.characters.count != pos + len {
                    pos++
                }
            }
        }
        
        self.selectedTextRange = self.textRangeFromPosition(self.positionFromPosition(self.beginningOfDocument, offset: pos)!, toPosition: self.positionFromPosition(self.beginningOfDocument, offset: pos + len)!)
        
        
        // Show editing menu
        self.showEditingMenu()
    }
    
    
    
    @objc private func startGrabberRepositioningTimerFired(timer: NSTimer) {
        // Invalidate timer
        _startGrabberRepositioningTimer?.invalidate()
        _startGrabberRepositioningTimer = nil
        
        
        // Snap start grabber
        self.snapStartGrabberTipPosition()
        _startGrabber.transform(animated: true)
        
    }
    
    
    
    @objc private func endGrabberRepositioningTimerFired(timer: NSTimer) {
        // Invalidate timer
        _endGrabberRepositioningTimer?.invalidate()
        _endGrabberRepositioningTimer = nil
        
        
        // Snap end grabber
        self.snapEndGrabberTipPosition()
        _endGrabber.transform(animated: true)
    }
    
    
    
    @objc private func startGrabberPanned(recognizer: UIPanGestureRecognizer) {
        self.hideEditingMenu()
        self.bringSubviewToFront(_startGrabber)
        
        _startGrabberIsBeingManipulated = true
        
        
        var animated = false
        
        // Began
        if recognizer.state == UIGestureRecognizerState.Began {
            _panOffset = recognizer.locationInView(_startGrabber)
            _panOffset.y = start_grabber_y_offset
            
            _startGrabber.forcedTipAlignment = .Center
            
            if !_startGrabber.extended {
                _startGrabber.extended = true
                animated = true
            }
        }
        
        
        // Always
        let location = recognizer.locationInView(self)
        let tip = CGPointMake(location.x - _panOffset.x + 0.5 * _startGrabber.frame.size.width,
                              location.y - _panOffset.y + 1.0 * _startGrabber.frame.size.height)
        _startGrabber.tipPosition = tip
        
        let pos = CGPointMake(tip.x, tip.y + start_grabber_tip_selection_offset)
        
        
        let textPosition = self.closestPositionToPoint(pos)!
        let posOffset = self.offsetFromPosition(self.beginningOfDocument, toPosition: textPosition)
        let endOffset = self.offsetFromPosition(self.beginningOfDocument, toPosition: self.selectedTextRange!.end)
        
        if posOffset < endOffset {
            self.selectedTextRange = self.textRangeFromPosition(textPosition, toPosition: self.selectedTextRange!.end)
        }
        
        
        // Ended
        if recognizer.state == UIGestureRecognizerState.Ended {
            self.snapStartGrabberTipPosition()
            
            animated = true
            
            self.showEditingMenu()
        }
        
        
        // Transform
        _startGrabber.transform(animated: animated)
    }
    
    
    
    @objc private func endGrabberPanned(recognizer: UIPanGestureRecognizer) {
        self.hideEditingMenu()
        self.bringSubviewToFront(_endGrabber)
        
        _endGrabberIsBeingManipulated = true
        
        
        var animated = false
        
        // Began
        if recognizer.state == UIGestureRecognizerState.Began {
            _panOffset = recognizer.locationInView(_endGrabber)
            _panOffset.y = 0.7 * _endGrabber.frame.size.height
            
            _endGrabber.forcedTipAlignment = .Center
            
            if !_endGrabber.extended {
                _endGrabber.extended = true
                animated = true
            }
        }
        
        
        // Always
        let location = recognizer.locationInView(self)
        let tip = CGPointMake(location.x - _panOffset.x + 0.5 * _endGrabber.frame.size.width,
                              location.y - _panOffset.y)
        _endGrabber.tipPosition = tip
        
        let pos = CGPointMake(tip.x, tip.y - end_grabber_tip_selection_offset)
        
        let textPosition = self.closestPositionToPoint(pos)!
        let posOffset = self.offsetFromPosition(self.beginningOfDocument, toPosition: textPosition)
        let startOffset = self.offsetFromPosition(self.beginningOfDocument, toPosition: self.selectedTextRange!.start)
        
        
        // Set selected range
        if !(self.selectedRange.length > 0 && posOffset <= startOffset) {
            if self.selectedRange.length == 0 {
                self.selectedTextRange = self.textRangeFromPosition(textPosition, toPosition: textPosition)
            } else {
                self.selectedTextRange = self.textRangeFromPosition(self.selectedTextRange!.start, toPosition: textPosition)
            }
        }
        
        
        // Ended
        if recognizer.state == UIGestureRecognizerState.Ended {
            self.snapEndGrabberTipPosition()
            
            animated = true
            
            self.showEditingMenu()
        }
        
        
        // Transform
        _endGrabber.transform(animated: animated)
    }
    
    
    
    private func snapStartGrabberTipPosition() {
        _startGrabber.forcedTipAlignment = nil
        _startGrabberIsBeingManipulated = false
        
        
        // Move start grabber to final position
        let topLeft = self.selectionCorners().0
        _startGrabber.tipPosition = topLeft
    }
    
    
    
    private func snapEndGrabberTipPosition() {
        _endGrabber.forcedTipAlignment = nil
        _endGrabberIsBeingManipulated = false
        
        
        // Move end grabber to final position
        let bottomRight = self.selectionCorners().1
        _endGrabber.tipPosition = bottomRight
    }
    
    
    
    
    
    
    
    // MARK: - UITextInput protocol
    
    class DejaTextSelectionRect: UITextSelectionRect {
        override var rect: CGRect {
            return CGRect(x: -100, y: -100, width: 4, height: 4)
        }
    }
    
    override public func selectionRectsForRange(range: UITextRange) -> [AnyObject] {
        return [DejaTextSelectionRect()]
    }
    
    
    
    
    
    
    
    // MARK: - UIResponder
    
    override public func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        if action == "selectAll:" || action == "select:" {
            return false
        } else {
            return super.canPerformAction(action, withSender: sender)
        }
    }
    
    
    
    
    
    
    
    // MARK: - Helpers
    
    private func showEditingMenu() {
        let menuController = UIMenuController.sharedMenuController()
        if !menuController.menuVisible {
            let rect = self.convertRect(_keyboardFrame, fromView: nil)
            menuController.setTargetRect(rect, inView: self)
            menuController.update()
            menuController.setMenuVisible(true, animated: false)
        }
    }
    
    
    
    private func hideEditingMenu() {
        let menuController = UIMenuController.sharedMenuController()
        if menuController.menuVisible {
            menuController.setMenuVisible(false, animated: false)
        }
    }
    
    
    
    private func distanceFrom(point point: CGPoint, toRect rect: CGRect) -> CGFloat {
        let center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))
        let x2 = pow(fabs(center.x - point.x), 2)
        let y2 = pow(fabs(center.y - point.y), 2)
        return sqrt(x2 + y2)
    }
    
    
    
    private func selectionCorners() -> (CGPoint, CGPoint) {
        if self.selectedTextRange!.empty {
            let rect = self.caretRectForPosition(self.selectedTextRange!.start)
            
            return (rect.origin, CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height))
        }
        
        let rects: [UITextSelectionRect] = super.selectionRectsForRange(self.selectedTextRange!) as! [UITextSelectionRect]
        
        var topLeft = CGPointMake(CGFloat.max, CGFloat.max)
        var bottomRight = CGPointMake(CGFloat.min, CGFloat.min)
        for r in rects {
            if r.rect.size.width < 0.5 || r.rect.size.height < 0.5 {
                continue
            }
            
            if r.rect.origin.y < topLeft.y {
                topLeft.y = r.rect.origin.y
                topLeft.x = r.rect.origin.x
            }
            
            if r.rect.origin.y + r.rect.size.height > ceil(bottomRight.y) {
                bottomRight.y = r.rect.origin.y + r.rect.size.height
                bottomRight.x = r.rect.origin.x + r.rect.size.width
            }
        }
        
        return (topLeft, bottomRight)
    }
}
 | 
	mit | 
| 
	srn214/Floral | 
	Floral/Pods/AutoInch/Sources/Inch.swift | 
	1 | 
	6082 | 
	//
//  Inch.swift
//  ┌─┐      ┌───────┐ ┌───────┐
//  │ │      │ ┌─────┘ │ ┌─────┘
//  │ │      │ └─────┐ │ └─────┐
//  │ │      │ ┌─────┘ │ ┌─────┘
//  │ └─────┐│ └─────┐ │ └─────┐
//  └───────┘└───────┘ └───────┘
//
//  Created by lee on 2018/1/22.
//  Copyright © 2018年 lee. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
public enum Inch {
    typealias Number = CGFloat
}
extension Inch {
    
    public enum Phone: Int, CaseIterable {
        case unknown = -1
        case i35
        case i40
        case i47
        case i55
        case i58Full
        case i61Full
        case i65Full
        
        var width: Number {
            switch self {
            case .unknown:  return 0
            case .i35:      return 320
            case .i40:      return 320
            case .i47:      return 375
            case .i55:      return 414
            case .i58Full:  return 375
            case .i61Full:  return 414
            case .i65Full:  return 414
            }
        }
        
        var height: Number {
            switch self {
            case .unknown:  return 0
            case .i35:      return 480
            case .i40:      return 568
            case .i47:      return 667
            case .i55:      return 736
            case .i58Full:  return 812
            case .i61Full:  return 896
            case .i65Full:  return 896
            }
        }
        
        var scale: CGFloat {
            switch self {
            case .unknown:  return 0
            case .i35:      return 2
            case .i40:      return 2
            case .i47:      return 2
            case .i55:      return 3
            case .i58Full:  return 3
            case .i61Full:  return 2
            case .i65Full:  return 3
            }
        }
        
        private var size: CGSize { return CGSize(width: width, height: height) }
        private var native: CGSize { return CGSize(width: width * scale, height: height * scale) }
        
        public static func type(size: CGSize = UIScreen.main.bounds.size,
                         scale: CGFloat = UIScreen.main.scale) -> Phone {
            let width = min(size.width, size.height) * scale
            let height = max(size.width, size.height) * scale
            let size = CGSize(width: width, height: height)
            
            switch size {
            case Phone.i35.native:     return .i35
            case Phone.i40.native:     return .i40
            case Phone.i47.native:     return .i47
            case Phone.i55.native:     return .i55
            case Phone.i58Full.native: return .i58Full
            case Phone.i61Full.native: return .i61Full
            case Phone.i65Full.native: return .i65Full
            default:                   return .unknown
            }
        }
        
        public static let current: Phone = type()
    }
}
extension Inch.Phone: Equatable {
    public static func == (lhs: Inch.Phone, rhs: Inch.Phone) -> Bool {
        return lhs.rawValue == rhs.rawValue
    }
}
extension Inch.Phone: Comparable {
    public static func < (lhs: Inch.Phone, rhs: Inch.Phone) -> Bool {
        return lhs.rawValue < rhs.rawValue
    }
}
extension Int: Inchable {}
extension Bool: Inchable {}
extension Float: Inchable {}
extension Double: Inchable {}
extension String: Inchable {}
extension CGRect: Inchable {}
extension CGSize: Inchable {}
extension CGFloat: Inchable {}
extension CGPoint: Inchable {}
extension UIImage: Inchable {}
extension UIColor: Inchable {}
extension UIFont: Inchable {}
extension UIEdgeInsets: Inchable {}
public protocol Inchable {
    
    func i35(_ value: Self) -> Self
    func i40(_ value: Self) -> Self
    func i47(_ value: Self) -> Self
    func i55(_ value: Self) -> Self
    func i58full(_ value: Self) -> Self
    func i61full(_ value: Self) -> Self
    func i65full(_ value: Self) -> Self
    
    func w320(_ value: Self) -> Self
    func w375(_ value: Self) -> Self
    func w414(_ value: Self) -> Self
}
extension Inchable {
    
    public func i35(_ value: Self) -> Self {
        return matching(type: .i35, value)
    }
    public func i40(_ value: Self) -> Self {
        return matching(type: .i40, value)
    }
    public func i47(_ value: Self) -> Self {
        return matching(type: .i47, value)
    }
    public func i55(_ value: Self) -> Self {
        return matching(type: .i55, value)
    }
    public func i58full(_ value: Self) -> Self {
        return matching(type: .i58Full, value)
    }
    public func i61full(_ value: Self) -> Self {
        return matching(type: .i61Full, value)
    }
    public func i65full(_ value: Self) -> Self {
        return matching(type: .i65Full, value)
    }
    public func ifull(_ value: Self) -> Self {
        return matching([.i58Full, .i61Full, .i65Full], value)
    }
    
    public func w320(_ value: Self) -> Self {
        return matching(width: 320, value)
    }
    public func w375(_ value: Self) -> Self {
        return matching(width: 375, value)
    }
    public func w414(_ value: Self) -> Self {
        return matching(width: 414, value)
    }
    
    private func matching(type: Inch.Phone, _ value: Self) -> Self {
        return Inch.Phone.current == type ? value : self
    }
    private func matching(width: Inch.Number, _ value: Self) -> Self {
        return Inch.Phone.current.width == width ? value : self
    }
    
    private func matching(_ types: [Inch.Phone], _ value: Self) -> Self {
        return types.contains(.current) ? value : self
    }
    private func matching(_ range: Range<Inch.Phone>, _ value: Self) -> Self {
        return range ~= .current ? value : self
    }
    private func matching(_ range: ClosedRange<Inch.Phone>, _ value: Self) -> Self {
        return range ~= .current ? value : self
    }
}
#endif
 | 
	mit | 
| 
	MarcoSantarossa/SwiftyToggler | 
	Tests/TestDoubles/SpyFeatureChangesObserver.swift | 
	1 | 
	1642 | 
	//
//  SpyFeatureChangesObserver.swift
//
//  Copyright (c) 2017 Marco Santarossa (https://marcosantadev.com/)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//
@testable import SwiftyToggler
class SpyFeatureChangesObserver: FeatureChangesObserver {
	private(set) var featureDidChangeCalledCount = 0
	private(set) var featureDidChangeNameArgument: String?
	private(set) var featureDidChangeIsEnableArgument: Bool?
	func featureDidChange(name: String, isEnabled: Bool) {
		featureDidChangeCalledCount += 1
		featureDidChangeNameArgument = name
		featureDidChangeIsEnableArgument = isEnabled
	}
}
 | 
	mit | 
| 
	bparish628/iFarm-Health | 
	iOS/iFarm-Health/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift | 
	4 | 
	13322 | 
	//
//  XAxisRendererHorizontalBarChart.swift
//  Charts
//
//  Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
//  A port of MPAndroidChart for iOS
//  Licensed under Apache License 2.0
//
//  https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
    import UIKit
#endif
open class XAxisRendererHorizontalBarChart: XAxisRenderer
{
    @objc internal var chart: BarChartView?
    
    @objc public init(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, transformer: Transformer?, chart: BarChartView?)
    {
        super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer)
        
        self.chart = chart
    }
    
    open override func computeAxis(min: Double, max: Double, inverted: Bool)
    {
        guard let
            viewPortHandler = self.viewPortHandler
            else { return }
        
        var min = min, max = max
        
        if let transformer = self.transformer
        {
            // calculate the starting and entry point of the y-labels (depending on
            // zoom / contentrect bounds)
            if viewPortHandler.contentWidth > 10 && !viewPortHandler.isFullyZoomedOutX
            {
                let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
                let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
                
                if inverted
                {
                    min = Double(p2.y)
                    max = Double(p1.y)
                }
                else
                {
                    min = Double(p1.y)
                    max = Double(p2.y)
                }
            }
        }
        
        computeAxisValues(min: min, max: max)
    }
    
    open override func computeSize()
    {
        guard let
            xAxis = self.axis as? XAxis
            else { return }
       
        let longest = xAxis.getLongestLabel() as NSString
        
        let labelSize = longest.size(withAttributes: [NSAttributedStringKey.font: xAxis.labelFont])
        
        let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5)
        let labelHeight = labelSize.height
        
        let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(rectangleWidth: labelSize.width, rectangleHeight:  labelHeight, degrees: xAxis.labelRotationAngle)
        
        xAxis.labelWidth = labelWidth
        xAxis.labelHeight = labelHeight
        xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5)
        xAxis.labelRotatedHeight = round(labelRotatedSize.height)
    }
    open override func renderAxisLabels(context: CGContext)
    {
        guard
            let xAxis = self.axis as? XAxis,
            let viewPortHandler = self.viewPortHandler
            else { return }
        
        if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil
        {
            return
        }
        
        let xoffset = xAxis.xOffset
        
        if xAxis.labelPosition == .top
        {
            drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
        }
        else if xAxis.labelPosition == .topInside
        {
            drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
        }
        else if xAxis.labelPosition == .bottom
        {
            drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
        }
        else if xAxis.labelPosition == .bottomInside
        {
            drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
        }
        else
        { // BOTH SIDED
            drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5))
            drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5))
        }
    }
    /// draws the x-labels on the specified y-position
    open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)
    {
        guard
            let xAxis = self.axis as? XAxis,
            let transformer = self.transformer,
            let viewPortHandler = self.viewPortHandler
            else { return }
        
        let labelFont = xAxis.labelFont
        let labelTextColor = xAxis.labelTextColor
        let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD
        
        let centeringEnabled = xAxis.isCenterAxisLabelsEnabled
        
        // pre allocate to save performance (dont allocate in loop)
        var position = CGPoint(x: 0.0, y: 0.0)
        
        for i in stride(from: 0, to: xAxis.entryCount, by: 1)
        {
            // only fill x values
            
            position.x = 0.0
            
            if centeringEnabled
            {
                position.y = CGFloat(xAxis.centeredEntries[i])
            }
            else
            {
                position.y = CGFloat(xAxis.entries[i])
            }
            
            transformer.pointValueToPixel(&position)
            
            if viewPortHandler.isInBoundsY(position.y)
            {
                if let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis)
                {
                    drawLabel(
                        context: context,
                        formattedLabel: label,
                        x: pos,
                        y: position.y,
                        attributes: [NSAttributedStringKey.font: labelFont, NSAttributedStringKey.foregroundColor: labelTextColor],
                        anchor: anchor,
                        angleRadians: labelRotationAngleRadians)
                }
            }
        }
    }
    
    @objc open func drawLabel(
        context: CGContext,
        formattedLabel: String,
        x: CGFloat,
        y: CGFloat,
        attributes: [NSAttributedStringKey : Any],
        anchor: CGPoint,
        angleRadians: CGFloat)
    {
        ChartUtils.drawText(
            context: context,
            text: formattedLabel,
            point: CGPoint(x: x, y: y),
            attributes: attributes,
            anchor: anchor,
            angleRadians: angleRadians)
    }
    
    open override var gridClippingRect: CGRect
    {
        var contentRect = viewPortHandler?.contentRect ?? CGRect.zero
        let dy = self.axis?.gridLineWidth ?? 0.0
        contentRect.origin.y -= dy / 2.0
        contentRect.size.height += dy
        return contentRect
    }
    
    fileprivate var _gridLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
    
    open override func drawGridLine(context: CGContext, x: CGFloat, y: CGFloat)
    {
        guard
            let viewPortHandler = self.viewPortHandler
            else { return }
        
        if viewPortHandler.isInBoundsY(y)
        {
            context.beginPath()
            context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: y))
            context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: y))
            context.strokePath()
        }
    }
    
    open override func renderAxisLine(context: CGContext)
    {
        guard
            let xAxis = self.axis as? XAxis,
            let viewPortHandler = self.viewPortHandler
            else { return }
        
        if !xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled
        {
            return
        }
        
        context.saveGState()
        
        context.setStrokeColor(xAxis.axisLineColor.cgColor)
        context.setLineWidth(xAxis.axisLineWidth)
        if xAxis.axisLineDashLengths != nil
        {
            context.setLineDash(phase: xAxis.axisLineDashPhase, lengths: xAxis.axisLineDashLengths)
        }
        else
        {
            context.setLineDash(phase: 0.0, lengths: [])
        }
        
        if xAxis.labelPosition == .top ||
            xAxis.labelPosition == .topInside ||
            xAxis.labelPosition == .bothSided
        {
            context.beginPath()
            context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
            context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom))
            context.strokePath()
        }
        
        if xAxis.labelPosition == .bottom ||
            xAxis.labelPosition == .bottomInside ||
            xAxis.labelPosition == .bothSided
        {
            context.beginPath()
            context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
            context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom))
            context.strokePath()
        }
        
        context.restoreGState()
    }
    
    open override func renderLimitLines(context: CGContext)
    {
        guard
            let xAxis = self.axis as? XAxis,
            let viewPortHandler = self.viewPortHandler,
            let transformer = self.transformer
            else { return }
        
        var limitLines = xAxis.limitLines
        
        if limitLines.count == 0
        {
            return
        }
        
        let trans = transformer.valueToPixelMatrix
        
        var position = CGPoint(x: 0.0, y: 0.0)
        
        for i in 0 ..< limitLines.count
        {
            let l = limitLines[i]
            
            if !l.isEnabled
            {
                continue
            }
            
            context.saveGState()
            defer { context.restoreGState() }
            
            var clippingRect = viewPortHandler.contentRect
            clippingRect.origin.y -= l.lineWidth / 2.0
            clippingRect.size.height += l.lineWidth
            context.clip(to: clippingRect)
            position.x = 0.0
            position.y = CGFloat(l.limit)
            position = position.applying(trans)
            
            context.beginPath()
            context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y))
            context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y))
            
            context.setStrokeColor(l.lineColor.cgColor)
            context.setLineWidth(l.lineWidth)
            if l.lineDashLengths != nil
            {
                context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!)
            }
            else
            {
                context.setLineDash(phase: 0.0, lengths: [])
            }
            
            context.strokePath()
            
            let label = l.label
            
            // if drawing the limit-value label is enabled
            if l.drawLabelEnabled && label.characters.count > 0
            {
                let labelLineHeight = l.valueFont.lineHeight
                
                let xOffset: CGFloat = 4.0 + l.xOffset
                let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset
                
                if l.labelPosition == .rightTop
                {
                    ChartUtils.drawText(context: context,
                        text: label,
                        point: CGPoint(
                            x: viewPortHandler.contentRight - xOffset,
                            y: position.y - yOffset),
                        align: .right,
                        attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor])
                }
                else if l.labelPosition == .rightBottom
                {
                    ChartUtils.drawText(context: context,
                        text: label,
                        point: CGPoint(
                            x: viewPortHandler.contentRight - xOffset,
                            y: position.y + yOffset - labelLineHeight),
                        align: .right,
                        attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor])
                }
                else if l.labelPosition == .leftTop
                {
                    ChartUtils.drawText(context: context,
                        text: label,
                        point: CGPoint(
                            x: viewPortHandler.contentLeft + xOffset,
                            y: position.y - yOffset),
                        align: .left,
                        attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor])
                }
                else
                {
                    ChartUtils.drawText(context: context,
                        text: label,
                        point: CGPoint(
                            x: viewPortHandler.contentLeft + xOffset,
                            y: position.y + yOffset - labelLineHeight),
                        align: .left,
                        attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor])
                }
            }
        }
    }
}
 | 
	apache-2.0 | 
| 
	ric2b/Vivaldi-browser | 
	thirdparty/macsparkle/Tests/SUSpotlightImporterTest.swift | 
	1 | 
	3671 | 
	//
//  SUSpotlightImporterTest.swift
//  Sparkle
//
//  Created by Mayur Pawashe on 8/27/16.
//  Copyright © 2016 Sparkle Project. All rights reserved.
//
import XCTest
class SUSpotlightImporterTest: XCTestCase
{
    func testUpdatingSpotlightBundles()
    {
        let fileManager = SUFileManager.default()
        let tempDirectoryURL = try! fileManager.makeTemporaryDirectory(withPreferredName: "Sparkle Unit Test Data", appropriateForDirectoryURL: URL(fileURLWithPath: NSHomeDirectory()))
        let bundleDirectory = tempDirectoryURL.appendingPathComponent("bundle.app")
        try! fileManager.makeDirectory(at: bundleDirectory)
        let innerDirectory = bundleDirectory.appendingPathComponent("foo")
        try! fileManager.makeDirectory(at: innerDirectory)
        try! Data().write(to: (bundleDirectory.appendingPathComponent("bar")), options: .atomicWrite)
        let importerDirectory = innerDirectory.appendingPathComponent("baz.mdimporter")
        try! fileManager.makeDirectory(at: importerDirectory)
        try! fileManager.makeDirectory(at: innerDirectory.appendingPathComponent("flag"))
        try! Data().write(to: (importerDirectory.appendingPathComponent("file")), options: .atomicWrite)
        let oldFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.path)
        let oldBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory.appendingPathComponent("bar").path)
        let oldImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.path)
        let oldFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.appendingPathComponent("flag").path)
        let oldFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.appendingPathComponent("file").path)
        sleep(1) // wait for clock to advance
        // Update spotlight bundles
        SUBinaryDeltaUnarchiver.updateSpotlightImporters(atBundlePath: bundleDirectory.path)
        let newFooDirectoryAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.path)
        XCTAssertEqual((newFooDirectoryAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFooDirectoryAttributes[FileAttributeKey.modificationDate] as! Date), 0)
        let newBarFileAttributes = try! FileManager.default.attributesOfItem(atPath: bundleDirectory.appendingPathComponent("bar").path)
        XCTAssertEqual((newBarFileAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldBarFileAttributes[FileAttributeKey.modificationDate] as! Date), 0)
        let newImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.path)
        XCTAssertGreaterThan((newImporterAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldImporterAttributes[FileAttributeKey.modificationDate] as! Date), 0)
        let newFlagAttributes = try! FileManager.default.attributesOfItem(atPath: innerDirectory.appendingPathComponent("flag").path)
        XCTAssertEqual((newFlagAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFlagAttributes[FileAttributeKey.modificationDate] as! Date), 0)
        let newFileInImporterAttributes = try! FileManager.default.attributesOfItem(atPath: importerDirectory.appendingPathComponent("file").path)
        XCTAssertEqual((newFileInImporterAttributes[FileAttributeKey.modificationDate] as! Date).timeIntervalSince(oldFileInImporterAttributes[FileAttributeKey.modificationDate] as! Date), 0)
        try! fileManager.removeItem(at: tempDirectoryURL)
    }
}
 | 
	bsd-3-clause | 
| 
	radex/swift-compiler-crashes | 
	crashes-fuzzing/07898-swift-declname-printpretty.swift | 
	11 | 
	229 | 
	// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func b{class A{class n{let t:d{struct B<T where h:a{let:T->g | 
	mit | 
| 
	Mobilette/MobiletteDashboardiOS | 
	MobiletteDashboardIOS/Classes/AppDelegate.swift | 
	1 | 
	2500 | 
	//
//  AppDelegate.swift
//  MobiletteDashboardIOS
//
//  Created by Romain ASNAR on 9/15/15.
//  Copyright (c) 2015 Mobilette. All rights reserved.
//
import UIKit
import OAuthSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        if let window = self.window {
            let rootWireframe = RootWireframe()
            rootWireframe.presentRootViewController(fromWindow: window)
        }
        return true
    }
    
    func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
        if (url.host == "oauth-callback") {
            OAuthSwift.handleOpenURL(url)
        }
        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:.
    }
}
 | 
	mit | 
| 
	KeepGoing2016/Swift- | 
	DUZB_XMJ/DUZB_XMJ/Classes/Home/Controller/GameViewController.swift | 
	1 | 
	6502 | 
	//
//  GameViewController.swift
//  DUZB_XMJ
//
//  Created by user on 16/12/29.
//  Copyright © 2016年 XMJ. All rights reserved.
//
import UIKit
fileprivate let kGameCellId = "kGameCellId"
fileprivate let kGameHeaderId = "kGameHeaderId"
fileprivate let kEdgeMargin:CGFloat = 10
fileprivate let kGameCellW = (kScreenW-2*kEdgeMargin)/3
fileprivate let kGameCellH = kGameCellW*6/5
class GameViewController: BaseViewController {
    fileprivate lazy var gameVM:GameViewModel = GameViewModel()
    
    fileprivate var supplementaryV:CollectionHeaderView?
    
    fileprivate lazy var topHeaderView:CollectionHeaderView = {
        let topHeaderView = CollectionHeaderView.headerView()
        topHeaderView.frame = CGRect(x: 0, y: -kSectionHeaderH-kIconViewH, width: kScreenW, height: kSectionHeaderH)
        topHeaderView.groupIconImg.image = UIImage(named: "Img_orange")
        topHeaderView.groupName.text = "常见"
        topHeaderView.moreBtn.isHidden = true
//        let tempF = topHeaderView.groupIconImg.frame
//        topHeaderView.groupIconImg.frame = CGRect(origin: tempF.origin, size: CGSize(width: 5, height: tempF.size.height))
        return topHeaderView
    }()
    
    fileprivate lazy var topIconView:IconView = {
        let topIconView = IconView(frame: CGRect(x: 0, y: -kIconViewH, width: kScreenW, height: kIconViewH))
        return topIconView
    }()
    
    fileprivate lazy var allContentView:UICollectionView = {[weak self] in
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.itemSize = CGSize(width: kGameCellW, height: kGameCellH)
        layout.headerReferenceSize = CGSize(width: kScreenW, height: kSectionHeaderH)
        layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin)
        let allContentView = UICollectionView(frame: (self?.view.bounds)!, collectionViewLayout: layout)
        allContentView.dataSource = self
        allContentView.backgroundColor = UIColor.white
        allContentView.register(UINib(nibName: "GameCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kGameCellId)
        allContentView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kGameHeaderId)
        allContentView.contentInset = UIEdgeInsets(top: kIconViewH+kSectionHeaderH, left: 0, bottom: 0, right: 0)
        allContentView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        return allContentView
    }()
    
    /*系统方法*/
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        requestData()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
//MARK:-设置UI
extension GameViewController{
    fileprivate func setupUI(){
        view.backgroundColor = UIColor.white
        
        view.addSubview(allContentView)
        
        allContentView.addSubview(topHeaderView)
        
        allContentView.addSubview(topIconView)
        
        baseContentView = allContentView
        isHiddenAnimation = false
        //请求数据
//        requestData()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        let tempF = topHeaderView.groupIconImg.frame
        topHeaderView.groupIconImg.frame = CGRect(origin: tempF.origin, size: CGSize(width: 5, height: tempF.size.height))
//        if #available(iOS 9.0, *) {
//            let headV = allContentView.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: 0)) as? CollectionHeaderView
//            let tempF2 = headV?.groupIconImg.frame
//            headV?.groupIconImg.frame = CGRect(origin: (tempF2?.origin)!, size: CGSize(width: 5, height: (tempF2?.size.height)!))
//        } else {
//            // Fallback on earlier versions
//        }
        
        let tempF2 = supplementaryV?.groupIconImg.frame
        supplementaryV?.groupIconImg.frame = CGRect(origin: (tempF2?.origin)!, size: CGSize(width: 5, height: (tempF2?.size.height)!))
        
       
        
    }
}
//MARK:-网络请求
extension GameViewController{
    fileprivate func requestData(){
        gameVM.loadGameData {
            DispatchQueue.global().async {
                var tempArr:[CellGroupModel] = [CellGroupModel]()
                for tempM in self.gameVM.gameModelArr[0..<10]{
                    //                let tempM = tempM as? GameModel
                    let groupM = CellGroupModel(dict: ["icon_url":tempM.icon_url,"tag_name":tempM.tag_name])
                    tempArr.append(groupM)
                }
                DispatchQueue.main.async {
                    
                    self.topIconView.dataModelArr = tempArr
                    
                    self.allContentView.reloadData()
//                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: { 
//                        self.isHiddenAnimation = true
//                    })
                    self.isHiddenAnimation = true
                }
            }
        }
    }
}
//MARK:-数据源
extension GameViewController:UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return gameVM.gameModelArr.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellId, for: indexPath) as! GameCollectionViewCell
        cell.gameModel = gameVM.gameModelArr[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kGameHeaderId, for: indexPath) as! CollectionHeaderView
        header.groupName.text = "全部"
        header.groupIconImg.image = UIImage(named: "Img_orange")
        header.moreBtn.isHidden = true
        supplementaryV = header
        return header
    }
}
 | 
	apache-2.0 | 
| 
	Onix-Systems/ios-mazazine-reader | 
	MazazineReaderTests/MazazineReaderTests.swift | 
	1 | 
	1422 | 
	// Copyright 2017 Onix-Systems
// 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
@testable import MazazineReader
class MazazineReaderTests: XCTestCase {
    
    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }
    
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    
    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }
    
    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }
    
}
 | 
	apache-2.0 | 
| 
	jtbandes/swift-compiler-crashes | 
	crashes-duplicates/26895-swift-lexer-lexidentifier.swift | 
	4 | 
	197 | 
	// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct S<T:T.b{enum B{"
s B
 | 
	mit | 
| 
	wordpress-mobile/WordPress-iOS | 
	WordPress/Classes/ViewRelated/Cells/InlineEditableMultiLineCell.swift | 
	1 | 
	1832 | 
	import Foundation
// UITableViewCell that displays an editable UITextView to allow text to be modified inline.
// The cell height resizes as the text is modified.
// The delegate is notified when:
// - The height is updated.
// - The text is updated.
protocol InlineEditableMultiLineCellDelegate: AnyObject {
    func textViewHeightUpdatedForCell(_ cell: InlineEditableMultiLineCell)
    func textUpdatedForCell(_ cell: InlineEditableMultiLineCell)
}
class InlineEditableMultiLineCell: UITableViewCell, NibReusable {
    // MARK: - Properties
    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var textViewMinHeightConstraint: NSLayoutConstraint!
    weak var delegate: InlineEditableMultiLineCellDelegate?
    // MARK: - View
    override func awakeFromNib() {
        super.awakeFromNib()
        configureCell()
    }
    func configure(text: String? = nil) {
        textView.text = text
        adjustHeight()
    }
}
// MARK: - UITextViewDelegate
extension InlineEditableMultiLineCell: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        delegate?.textUpdatedForCell(self)
        adjustHeight()
    }
}
// MARK: - Private Extension
private extension InlineEditableMultiLineCell {
    func configureCell() {
        textView.font = .preferredFont(forTextStyle: .body)
        textView.textColor = .text
        textView.backgroundColor = .clear
    }
    func adjustHeight() {
        let originalHeight = textView.frame.size.height
        textView.sizeToFit()
        let textViewHeight = ceilf(Float(max(textView.frame.size.height, textViewMinHeightConstraint.constant)))
        textView.frame.size.height = CGFloat(textViewHeight)
        if textViewHeight != Float(originalHeight) {
            delegate?.textViewHeightUpdatedForCell(self)
        }
    }
}
 | 
	gpl-2.0 | 
| 
	Roommate-App/roomy | 
	roomy/Pods/IBAnimatable/Sources/Protocols/Designable/TintDesignable.swift | 
	3 | 
	1522 | 
	//
//  Created by Jake Lin on 11/24/15.
//  Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
public protocol TintDesignable: class {
  /**
   Opacity in tint Color (White): from 0 to 1
   */
  var tintOpacity: CGFloat { get set }
  /**
   Opacity in shade Color (Black): from 0 to 1
   */
  var shadeOpacity: CGFloat { get set }
  /**
   tone color
   */
  var toneColor: UIColor? { get set }
  /**
   Opacity in tone color: from 0 to 1
   */
  var toneOpacity: CGFloat { get set }
}
public extension TintDesignable where Self: UIView {
  /**
   configureTintedColor method, should be called in layoutSubviews() method
   */
  public func configureTintedColor() {
    if !tintOpacity.isNaN && tintOpacity >= 0 && tintOpacity <= 1 {
      addColorSubview(color: .white, opacity: tintOpacity)
    }
    if !shadeOpacity.isNaN && shadeOpacity >= 0 && shadeOpacity <= 1 {
      addColorSubview(color: .black, opacity: shadeOpacity)
    }
    if let toneColor = toneColor {
      if !toneOpacity.isNaN && toneOpacity >= 0 && toneOpacity <= 1 {
        addColorSubview(color: toneColor, opacity: toneOpacity)
      }
    }
  }
  fileprivate func addColorSubview(color: UIColor, opacity: CGFloat) {
    let subview = UIView(frame: bounds)
    subview.backgroundColor = color
    subview.alpha = opacity
    if layer.cornerRadius > 0 {
      subview.layer.cornerRadius = layer.cornerRadius
    }
    subview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    insertSubview(subview, at: 0)
  }
}
 | 
	mit | 
| 
	Off-Piste/Trolley.io | 
	Trolley/Core/Networking/Third Party/Reachability/Reachability.swift | 
	2 | 
	10209 | 
	/*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Reachability.swift version 2.2beta2
import SystemConfiguration
import PromiseKit
import Foundation
public enum ReachabilityError: Error {
    
    case FailedToCreateWithAddress(sockaddr_in)
    
    case FailedToCreateWithHostname(String)
    
    case UnableToSetCallback
    
    case UnableToSetDispatchQueue
    
    case guardFailed(String)
    
    case objectNil(Any?)
    
}
public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
    guard let info = info else { return }
    
    let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
    DispatchQueue.main.async { 
        reachability.reachabilityChanged()
    }
}
public class Reachability {
    public typealias NetworkReachable = (Reachability) -> ()
    public typealias NetworkUnreachable = (Reachability) -> ()
    public enum NetworkStatus: CustomStringConvertible {
        case notReachable, reachableViaWiFi, reachableViaWWAN
        public var description: String {
            switch self {
            case .reachableViaWWAN: return "Cellular"
            case .reachableViaWiFi: return "WiFi"
            case .notReachable: return "No Connection"
            }
        }
    }
    public var whenReachable: NetworkReachable?
    public var whenUnreachable: NetworkUnreachable?
    public var reachableOnWWAN: Bool
    public var currentReachabilityString: String {
        return "\(currentReachabilityStatus)"
    }
    public var currentReachabilityStatus: NetworkStatus {
        guard isReachable else { return .notReachable }
        
        if isReachableViaWiFi {
            return .reachableViaWiFi
        }
        if isRunningOnDevice {
            return .reachableViaWWAN
        }
        
        return .notReachable
    }
    
    fileprivate var previousFlags: SCNetworkReachabilityFlags?
    
    fileprivate var isRunningOnDevice: Bool = {
        #if (arch(i386) || arch(x86_64)) && os(iOS)
            return false
        #else
            return true
        #endif
    }()
    
    fileprivate var notifierRunning = false
    fileprivate var reachabilityRef: SCNetworkReachability?
    
    fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
    
    required public init(reachabilityRef: SCNetworkReachability) {
        reachableOnWWAN = true
        self.reachabilityRef = reachabilityRef
    }
    
    public convenience init?(hostname: String) {
        
        guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
        
        self.init(reachabilityRef: ref)
    }
    
    public convenience init?() {
        
        var zeroAddress = sockaddr()
        zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
        zeroAddress.sa_family = sa_family_t(AF_INET)
        
        guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, {
            SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
        }) else { return nil }
        
        self.init(reachabilityRef: ref)
    }
    
    deinit {
        stopNotifier()
        reachabilityRef = nil
        whenReachable = nil
        whenUnreachable = nil
    }
}
extension Reachability: CustomStringConvertible {
    
    // MARK: - *** Notifier methods ***
    public func startNotifier() throws {
        
        guard let reachabilityRef = reachabilityRef, !notifierRunning else { return }
        
        var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
        context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())        
        if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
            stopNotifier()
            throw ReachabilityError.UnableToSetCallback
        }
        
        if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
            stopNotifier()
            throw ReachabilityError.UnableToSetDispatchQueue
        }
        
        // Perform an intial check
        reachabilitySerialQueue.async {
            self.reachabilityChanged()
        }
        
        notifierRunning = true
    }
    
    public func stopNotifier() {
        defer { notifierRunning = false }
        guard let reachabilityRef = reachabilityRef else { return }
        TRLCoreNetworkingLogger.debug("Stopping Reachability Notifier")
        
        SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
        SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
    }
    
    // MARK: - *** Connection test methods ***
    public var isReachable: Bool {
        
        guard isReachableFlagSet else { return false }
        
        if isConnectionRequiredAndTransientFlagSet {
            return false
        }
        
        if isRunningOnDevice {
            if isOnWWANFlagSet && !reachableOnWWAN {
                // We don't want to connect when on 3G.
                return false
            }
        }
        
        return true
    }
    
    public var isReachableViaWWAN: Bool {
        // Check we're not on the simulator, we're REACHABLE and check we're on WWAN
        return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
    }
    
    public var isReachableViaWiFi: Bool {
        
        // Check we're reachable
        guard isReachableFlagSet else { return false }
        
        // If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
        guard isRunningOnDevice else { return true }
        
        // Check we're NOT on WWAN
        return !isOnWWANFlagSet
    }
    
    public var description: String {
        
        let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
        let R = isReachableFlagSet ? "R" : "-"
        let c = isConnectionRequiredFlagSet ? "c" : "-"
        let t = isTransientConnectionFlagSet ? "t" : "-"
        let i = isInterventionRequiredFlagSet ? "i" : "-"
        let C = isConnectionOnTrafficFlagSet ? "C" : "-"
        let D = isConnectionOnDemandFlagSet ? "D" : "-"
        let l = isLocalAddressFlagSet ? "l" : "-"
        let d = isDirectFlagSet ? "d" : "-"
        
        return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
    }
}
fileprivate extension Reachability {
    
    func reachabilityChanged() {
        
        let flags = reachabilityFlags
        
        guard previousFlags != flags else { return }
        
        let block = isReachable ? whenReachable : whenUnreachable
        block?(self)
        
        TRLCoreNetworkingLogger.debug("Reachability Changed", self.currentReachabilityString)
        NotificationCenter.default.post(name: ReachabilityChangedNotification, object:self)
        
        previousFlags = flags
    }
    
    var isOnWWANFlagSet: Bool {
        #if os(iOS)
            return reachabilityFlags.contains(.isWWAN)
        #else
            return false
        #endif
    }
    var isReachableFlagSet: Bool {
        return reachabilityFlags.contains(.reachable)
    }
    var isConnectionRequiredFlagSet: Bool {
        return reachabilityFlags.contains(.connectionRequired)
    }
    var isInterventionRequiredFlagSet: Bool {
        return reachabilityFlags.contains(.interventionRequired)
    }
    var isConnectionOnTrafficFlagSet: Bool {
        return reachabilityFlags.contains(.connectionOnTraffic)
    }
    var isConnectionOnDemandFlagSet: Bool {
        return reachabilityFlags.contains(.connectionOnDemand)
    }
    var isConnectionOnTrafficOrDemandFlagSet: Bool {
        return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
    }
    var isTransientConnectionFlagSet: Bool {
        return reachabilityFlags.contains(.transientConnection)
    }
    var isLocalAddressFlagSet: Bool {
        return reachabilityFlags.contains(.isLocalAddress)
    }
    var isDirectFlagSet: Bool {
        return reachabilityFlags.contains(.isDirect)
    }
    var isConnectionRequiredAndTransientFlagSet: Bool {
        return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
    }
    
    var reachabilityFlags: SCNetworkReachabilityFlags {
        
        guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() }
        
        var flags = SCNetworkReachabilityFlags()
        let gotFlags = withUnsafeMutablePointer(to: &flags) {
            SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
        }
        
        if gotFlags {
            return flags
        } else {
            return SCNetworkReachabilityFlags()
        }
    }
}
 | 
	mit | 
| 
	mpercich/Calendarize | 
	ios/Calendarize/ViewController.swift | 
	1 | 
	510 | 
	//
//  ViewController.swift
//  Calendarize
//
//  Created by Percich Michele (UniCredit Business Integrated Solutions) on 27/01/17.
//  Copyright © 2017 Michele Percich. All rights reserved.
//
import Cocoa
class ViewController: NSViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}
 | 
	mit | 
| 
	narner/AudioKit | 
	AudioKit/iOS/AudioKit/User Interface/AKStepper.swift | 
	1 | 
	5871 | 
	//
//  AKStepper.swift
//  AudioKit for iOS
//
//  Created by Aurelius Prochazka on 3/11/17.
//  Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
import AudioKit
import UIKit
/// Incrementor view, normally used for MIDI presets, but could be useful elsehwere
open class AKStepper: UIView {
    var plusPath = UIBezierPath()
    var minusPath = UIBezierPath()
    /// Text / label to display
    open var text = "Value"
    /// Current value
    open var value: MIDIByte
    /// Function to call on change
    open var callback: (MIDIByte) -> Void
    /// Handle new touches
    override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            let touchLocation = touch.location(in: self)
            if minusPath.contains(touchLocation) {
                if value > 1 {
                    value -= 1
                }
            }
            if plusPath.contains(touchLocation) {
                if value < 127 {
                    value += 1
                }
            }
            self.callback(value)
            setNeedsDisplay()
        }
    }
    /// Initialize the stepper view
    @objc public init(text: String,
                      value: MIDIByte,
                      frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 60),
                      callback: @escaping (MIDIByte) -> Void) {
        self.callback = callback
        self.value = value
        self.text = text
        super.init(frame: frame)
    }
    /// Initialize within Interface Builder
    required public init?(coder aDecoder: NSCoder) {
        self.callback = { filename in return }
        self.value = 0
        self.text = "Value"
        super.init(coder: aDecoder)
    }
    /// Draw the stepper
    override open func draw(_ rect: CGRect) {
        //// General Declarations
        let context = UIGraphicsGetCurrentContext()!
        //// Color Declarations
        let red = UIColor(red: 1.000, green: 0.150, blue: 0.061, alpha: 1.000)
        let gray = UIColor(red: 0.866, green: 0.872, blue: 0.867, alpha: 0.925)
        let green = UIColor(red: 0.000, green: 0.977, blue: 0.000, alpha: 1.000)
        //// background Drawing
        let backgroundPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 440, height: 60))
        gray.setFill()
        backgroundPath.fill()
        //// textLabel Drawing
        let textLabelRect = CGRect(x: 68, y: 0, width: 304, height: 60)
        let textLabelStyle = NSMutableParagraphStyle()
        textLabelStyle.alignment = .left
        let textLabelInset: CGRect = textLabelRect.insetBy(dx: 10, dy: 0)
        let textLabelTextHeight: CGFloat = text.boundingRect(with: CGSize(width: textLabelInset.width,
                                                                          height: CGFloat.infinity),
                                                             options: .usesLineFragmentOrigin,
                                                             attributes: nil,
                                                             context: nil).height
        context.saveGState()
        context.clip(to: textLabelInset)
        let newText = "\(text): \(value)"
        newText.draw(in: CGRect(x: textLabelInset.minX,
                                y: textLabelInset.minY + (textLabelInset.height - textLabelTextHeight) / 2,
                                width: textLabelInset.width,
                                height: textLabelTextHeight),
                     withAttributes: nil)
        context.restoreGState()
        //// minusGroup
        //// minusRectangle Drawing
        let minusRectanglePath = UIBezierPath(roundedRect: CGRect(x: 4, y: 5, width: 60, height: 50), cornerRadius: 16)
        red.setFill()
        minusRectanglePath.fill()
        UIColor.black.setStroke()
        minusRectanglePath.lineWidth = 2
        minusRectanglePath.stroke()
        //// minus Drawing
        minusPath = UIBezierPath(rect: CGRect(x: 19, y: 25, width: 31, height: 10))
        UIColor.black.setFill()
        minusPath.fill()
        //// plusGroup
        //// plusRectangle Drawing
        let plusRectanglePath = UIBezierPath(roundedRect: CGRect(x: 376, y: 5, width: 60, height: 50), cornerRadius: 16)
        green.setFill()
        plusRectanglePath.fill()
        UIColor.black.setStroke()
        plusRectanglePath.lineWidth = 2
        plusRectanglePath.stroke()
        //// plus Drawing
        plusPath = UIBezierPath()
        plusPath.move(to: CGPoint(x: 411, y: 15))
        plusPath.addCurve(to: CGPoint(x: 411, y: 25),
                          controlPoint1: CGPoint(x: 411, y: 15),
                          controlPoint2: CGPoint(x: 411, y: 19.49))
        plusPath.addLine(to: CGPoint(x: 421, y: 25))
        plusPath.addLine(to: CGPoint(x: 421, y: 35))
        plusPath.addLine(to: CGPoint(x: 411, y: 35))
        plusPath.addCurve(to: CGPoint(x: 411, y: 45),
                          controlPoint1: CGPoint(x: 411, y: 40.51),
                          controlPoint2: CGPoint(x: 411, y: 45))
        plusPath.addLine(to: CGPoint(x: 401, y: 45))
        plusPath.addCurve(to: CGPoint(x: 401, y: 35),
                          controlPoint1: CGPoint(x: 401, y: 45),
                          controlPoint2: CGPoint(x: 401, y: 40.51))
        plusPath.addLine(to: CGPoint(x: 391, y: 35))
        plusPath.addLine(to: CGPoint(x: 391, y: 25))
        plusPath.addLine(to: CGPoint(x: 401, y: 25))
        plusPath.addCurve(to: CGPoint(x: 401, y: 15),
                          controlPoint1: CGPoint(x: 401, y: 19.49),
                          controlPoint2: CGPoint(x: 401, y: 15))
        plusPath.addLine(to: CGPoint(x: 411, y: 15))
        plusPath.addLine(to: CGPoint(x: 411, y: 15))
        plusPath.close()
        UIColor.black.setFill()
        plusPath.fill()
    }
}
 | 
	mit | 
| 
	27629678/web_dev | 
	client/Demo/websocket/WSUploadFileViewController.swift | 
	1 | 
	889 | 
	//
//  WSUploadFileViewController.swift
//  Demo
//
//  Created by hzyuxiaohua on 2017/1/17.
//  Copyright © 2017年 XY Network Co., Ltd. All rights reserved.
//
import UIKit
class WSUploadFileViewController: UIViewController {
    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.
    }
    
    /*
    // MARK: - Navigation
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
}
 | 
	mit | 
| 
	touchopia/SwiftStickers | 
	StickersApp/StickersApp/AppDelegate.swift | 
	2 | 
	421 | 
	//
//  AppDelegate.swift
//  StickersApp
//
//  Created by Phil Wright on 9/1/15.
//  Copyright © 2015 Touchopia, LLC. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        return true
    }
}
 | 
	mit | 
| 
	feliperuzg/CleanExample | 
	CleanExample/Authentication/View/LoginPresenterProtocol.swift | 
	1 | 
	294 | 
	//
//  File.swift
//  CleanExample
//
//  Created by Felipe Ruz on 19-07-17.
//  Copyright © 2017 Felipe Ruz. All rights reserved.
//
import Foundation
protocol LoginPresenterProtocol {
    func doLogin(_ user: String, password: String)
    func attachView(_ loginView: LoginViewProtocol)
}
 | 
	mit | 
| 
	younata/RSSClient | 
	TethysAppSpecs/UI/Account/OAuthLoginControllerSpec.swift | 
	1 | 
	9237 | 
	import Quick
import UIKit
import Nimble
import Result
import CBGPromise
@testable import TethysKit
@testable import Tethys
final class OAuthLoginControllerSpec: QuickSpec {
    override func spec() {
        var subject: OAuthLoginController!
        var accountService: FakeAccountService!
        var mainQueue: FakeOperationQueue!
        var authenticationSessions: [ASWebAuthenticationSession] = []
        beforeEach {
            authenticationSessions = []
            accountService = FakeAccountService()
            mainQueue = FakeOperationQueue()
            mainQueue.runSynchronously = true
            subject = OAuthLoginController(accountService: accountService, mainQueue: mainQueue, clientId: "testClientId") {
                let session = ASWebAuthenticationSession(url: $0, callbackURLScheme: $1, completionHandler: $2)
                authenticationSessions.append(session)
                return session
            }
        }
        it("does not yet create any authentication sessions") {
            expect(authenticationSessions).to(beEmpty())
        }
        describe("-begin()") {
            var future: Future<Result<Account, TethysError>>!
            var window: UIWindow!
            beforeEach {
                window = UIWindow()
                subject.window = window
                future = subject.begin()
            }
            it("creates an authentication session") {
                expect(authenticationSessions).to(haveCount(1))
            }
            it("starts the created authentication session") {
                expect(authenticationSessions.last?.began).to(beTrue())
            }
            it("sets the session's presentationContextProvider") {
                expect(authenticationSessions.last?.presentationContextProvider).toNot(beNil())
                let provider = authenticationSessions.last?.presentationContextProvider
                expect(provider?.presentationAnchor(for: authenticationSessions.last!)).to(be(window))
            }
            it("configures the authentication session for inoreader with a custom redirect") {
                guard let receivedURL = authenticationSessions.last?.url else { return }
                guard let components = URLComponents(url: receivedURL, resolvingAgainstBaseURL: false) else {
                    fail("Unable to construct URLComponents from \(receivedURL)")
                    return
                }
                expect(components.scheme).to(equal("https"), description: "Should make a request to an https url")
                expect(components.host).to(equal("www.inoreader.com"), description: "Should make a request to inoreader")
                expect(components.path).to(equal("/oauth2/auth"), description: "Should make a request to the oauth endpoint")
                expect(components.queryItems).to(haveCount(5), description: "Should have 5 query items")
                expect(components.queryItems).to(contain(
                    URLQueryItem(name: "redirect_uri", value: "https://tethys.younata.com/oauth"),
                    URLQueryItem(name: "response_type", value: "code"),
                    URLQueryItem(name: "scope", value: "read write"),
                    URLQueryItem(name: "client_id", value: "testClientId")
                ))
                guard let stateItem = (components.queryItems ?? []).first(where: { $0.name == "state" }) else {
                    fail("No state query item")
                    return
                }
                expect(stateItem.value).toNot(beNil())
            }
            it("sets the expected callback scheme") {
                expect(authenticationSessions.last?.callbackURLScheme).to(equal("rnews"))
            }
            describe("when the user finishes the session successfully") {
                describe("and everything is hunky-dory") {
                    beforeEach {
                        guard let receivedURL = authenticationSessions.last?.url else { return }
                        guard let components = URLComponents(url: receivedURL, resolvingAgainstBaseURL: false) else {
                            return
                        }
                        guard let stateItem = (components.queryItems ?? []).first(where: { $0.name == "state" }) else {
                            return
                        }
                        authenticationSessions.last?.completionHandler(
                            url(base: "rnews://oauth",
                                queryItems: ["code": "authentication_code", "state": stateItem.value!]),
                            nil
                        )
                    }
                    it("tells the account service to update it's credentials with the authentication code") {
                        expect(accountService.authenticateCalls).to(equal(["authentication_code"]))
                    }
                    describe("and the account service succeeds") {
                        beforeEach {
                            accountService.authenticatePromises.last?.resolve(.success(Account(
                                kind: .inoreader,
                                username: "a username",
                                id: "an id"
                            )))
                        }
                        it("resolves the future with the account") {
                            expect(future).to(beResolved())
                            expect(future.value?.value).to(equal(Account(
                                kind: .inoreader,
                                username: "a username",
                                id: "an id"
                            )))
                        }
                    }
                    describe("and the account service fails") {
                        beforeEach {
                            accountService.authenticatePromises.last?.resolve(.failure(.unknown))
                        }
                        it("resolves the future with the error") {
                            expect(future).to(beResolved())
                            expect(future.value?.error).to(equal(.unknown))
                        }
                    }
                }
                describe("and the csrf doesn't match") {
                    let csrfURL = url(base: "rnews://oauth",
                    queryItems: ["code": "authentication_code", "state": "badValue"])
                    beforeEach {
                        authenticationSessions.last?.completionHandler(
                            csrfURL,
                            nil
                        )
                    }
                    it("resolves the future with an invalidResponse error") {
                        expect(future).to(beResolved())
                        guard let error = future.value?.error else { fail("error not set"); return }
                        switch error {
                        case .network(let url, let networkError):
                            let body = (csrfURL.query ?? "").data(using: .utf8)!
                            expect(networkError).to(equal(.badResponse(body)))
                            expect(url.absoluteString.hasPrefix("https://www.inoreader.com/oauth2/auth")).to(
                                beTruthy(),
                                description: "Expected url to start with https://www.inoreader.com/oauth2/auth"
                            )
                        default:
                            fail("Expected error to be a badResponse network error, got \(error)")
                        }
                    }
                }
            }
            describe("when the user fails to login") {
                beforeEach {
                    let error = NSError(
                        domain: ASWebAuthenticationSessionErrorDomain,
                        code: ASWebAuthenticationSessionError.Code.canceledLogin.rawValue,
                        userInfo: nil)
                    authenticationSessions.last?.completionHandler(nil, error)
                }
                it("resolves the future with a cancelled error") {
                    expect(future).to(beResolved())
                    guard let error = future.value?.error else { fail("error not set"); return }
                    switch error {
                    case .network(let url, let networkError):
                        expect(networkError).to(equal(.cancelled))
                        expect(url.absoluteString.hasPrefix("https://www.inoreader.com/oauth2/auth")).to(
                            beTruthy(),
                            description: "Expected url to start with https://www.inoreader.com/oauth2/auth"
                        )
                    default:
                        fail("Expected error to be a cancelled network error, got \(error)")
                    }
                }
            }
        }
    }
}
func url(base: String, queryItems: [String: String]) -> URL {
    var components = URLComponents(string: base)!
    components.queryItems = queryItems.map { key, value in
        return URLQueryItem(name: key, value: value)
    }
    return components.url!
}
 | 
	mit | 
| 
	alreadyRight/Swift-algorithm | 
	循环引用/循环引用/ViewController.swift | 
	1 | 
	1096 | 
	//
//  ViewController.swift
//  循环引用
//
//  Created by 周冰烽 on 2017/12/8.
//  Copyright © 2017年 周冰烽. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
    
    var completionCallBack:(()->())?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //bloack 中如果出现 self. 要特别小心
        //'循环引用' 单方向对引用不会产生循环引用!
        //- 只是闭包最self进行了copy,闭包执行完成之后会自动销毁,同时释放对self的引用
        //- 同时需要self对闭包引用
        loadData {
            print(self.view)
        }
    }
    func loadData(completion:@escaping ()->()) -> () {
        //使用属性记录闭包
        completionCallBack = completion
        //异步
        DispatchQueue.global().async {
            print("耗时操作")
            DispatchQueue.main.async {
                //回调,执行闭包
                completion()
            }
        }
    }
    //类似于 OC 的dealloc
    deinit {
        print("我走了")
    }
}
 | 
	mit | 
| 
	thinkclay/FlourishUI | 
	Pod/Classes/ToggleSwitch.swift | 
	1 | 
	5375 | 
	import UIKit
public class ToggleButton: UIView
{
  
  var active: Bool = false
  
  public var activeBackgroundColor = UIColor(hex: "#6B60AB") {
    didSet {
      setNeedsDisplay()
    }
  }
  public var activeBorderColor = UIColor(hex: "#8579CE") {
    didSet {
      setNeedsDisplay()
    }
  }
  public var activeInnerShadowColor = UIColor(rgba: [255, 255, 255, 0.5]) {
    didSet {
      setNeedsDisplay()
    }
  }
  public var disabledBackgroundColor = UIColor(hex: "#4D428E") {
    didSet {
      setNeedsDisplay()
    }
  }
  public var disabledBorderColor = UIColor(hex: "#5C509D") {
    didSet {
      setNeedsDisplay()
    }
  }
  public var disabledInnerShadowColor = UIColor(rgba: [255, 255, 255, 0.14]) {
    didSet {
      setNeedsDisplay()
    }
  }
  
  override init(frame: CGRect)
  {
    super.init(frame: frame)
    
    backgroundColor = .clear
  }
  
  required public init?(coder aDecoder: NSCoder)
  {
    fatalError("init(coder:) has not been implemented")
  }
  
  override public func draw(_ rect: CGRect)
  {
    let buttonFill = active ? activeBackgroundColor : disabledBackgroundColor
    let buttonStroke = active ? activeBorderColor : disabledBorderColor
    let innerShadow = active ? activeInnerShadowColor : disabledInnerShadowColor
    let x: CGFloat = active ? 35 : 0
    let context = UIGraphicsGetCurrentContext()!
    
    // Oval with drop shadow
    let ovalPath = UIBezierPath(ovalIn: CGRect(x: 2, y: 1, width: 20, height: 20))
    context.saveGState()
    context.setShadow(offset: CGSize(width: 0.1, height: -0.1), blur: 2, color: UIColor.black.cgColor)
    buttonFill.setFill()
    ovalPath.fill()
    
    // Inner shadow
    context.saveGState()
    context.clip(to: ovalPath.bounds)
    context.setShadow(offset: CGSize.zero, blur: 0)
    context.setAlpha(innerShadow.cgColor.alpha)
    context.beginTransparencyLayer(auxiliaryInfo: nil)
    context.setShadow(offset: CGSize(width: 0.1, height: 1), blur: 3, color: UIColor.white.cgColor)
    context.setBlendMode(.sourceOut)
    context.beginTransparencyLayer(auxiliaryInfo: nil)
    
    let ovalOpaqueShadow = innerShadow.withAlphaComponent(1)
    ovalOpaqueShadow.setFill()
    ovalPath.fill()
    
    context.endTransparencyLayer()
    context.endTransparencyLayer()
    context.restoreGState()
    context.restoreGState()
    
    buttonStroke.setStroke()
    ovalPath.lineWidth = 1
    ovalPath.stroke()
    
    frame.origin.x = x
  }
}
public class ToggleSlide: UIView
{
  
  var active: Bool = false
  
  public var activeBackgroundColor = UIColor(hex: "#514398") {
    didSet {
      setNeedsDisplay()
    }
  }
  public var activeBorderColor = UIColor(hex: "#5B4CA9") {
    didSet {
      setNeedsDisplay()
    }
  }
  public var disabledBackgroundColor = UIColor(hex: "#382B76") {
    didSet {
      setNeedsDisplay()
    }
  }
  public var disabledBorderColor = UIColor(hex: "#4B3E8D") {
    didSet {
      setNeedsDisplay()
    }
  }
  
  override init(frame: CGRect)
  {
    super.init(frame: frame)
    
    backgroundColor = .clear
  }
  
  required public init?(coder aDecoder: NSCoder)
  {
    fatalError("init(coder:) has not been implemented")
  }
  
  override public func draw(_ rect: CGRect)
  {
    let slideFill = active ? activeBackgroundColor : disabledBackgroundColor
    let slideStroke = active ? activeBorderColor : disabledBorderColor
    let background = UIBezierPath(roundedRect: CGRect(x: 1, y: 7, width: 48, height: 10), cornerRadius: 10)
    background.lineWidth = 1
    slideFill.setFill()
    background.fill()
    slideStroke.setStroke()
    background.stroke()
  }
}
public class ToggleLabel: UIButton
{
  override init(frame: CGRect)
  {
    super.init(frame: frame)
  }
  
  required public init?(coder aDecoder: NSCoder)
  {
    fatalError("init(coder:) has not been implemented")
  }
}
open class ToggleSwitch: UIView
{
  public var active: Bool = false {
    didSet {
      button.active = active
      slide.active = active
      button.setNeedsDisplay()
      slide.setNeedsDisplay()
    }
  }
  public var button = ToggleButton(frame: CGRect(x: 0, y: 1, width: 24, height: 24))
  public var slide = ToggleSlide(frame: CGRect(x: 4, y: 0, width: 60, height: 20))
  public var label = ToggleLabel(frame: CGRect(x: 70, y: 0, width: 100, height: 22))
  public var toggleCallback: (() -> ())?
  
  override public init(frame: CGRect)
  {
    super.init(frame: frame)
    
    backgroundColor = .clear
    
    toggleCallback = { print("toggle init") }
    
    button.active = active
    slide.active = active
    
    addSubview(slide)
    addSubview(button)
    addSubview(label)
    
    label.addTarget(self, action: #selector(toggleHandler), for: .touchUpInside)
    addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleHandler)))
    addGestureRecognizer(UISwipeGestureRecognizer(target: self, action: #selector(toggleHandler)))
  }
  
  required public init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
    @objc public func toggleHandler()
  {
    UIView.animate(
      withDuration: 0.15,
      delay: 0.0,
      options: .curveEaseIn,
      animations: {
        self.button.frame.origin.x = self.active ? 0 : 35
    },
      completion: {
        _ in
        self.active = !self.active
        self.toggleCallback!()
    }
    )
  }
  
}
 | 
	mit | 
| 
	RxLeanCloud/rx-lean-swift | 
	src/RxLeanCloudSwift/Public/RxAVCQL.swift | 
	1 | 
	1289 | 
	//
//  RxAVCQL.swift
//  RxLeanCloudSwift
//
//  Created by WuJun on 14/12/2017.
//  Copyright © 2017 LeanCloud. All rights reserved.
//
import Foundation
import RxSwift
public class RxAVCQL<TEntity> where TEntity: IAVQueryable {
    public var cql: String
    public var placeholders: Array<Any>?
    public init(cql: String) {
        self.cql = cql
    }
    public func execute() -> Observable<Array<TEntity>> {
        var url = "/cloudQuery?cql=\(self.cql)"
        if let pValues = self.placeholders {
            let pStr = AVCorePlugins.sharedInstance.avEncoder.encode(value: pValues)
            url = "\(url)&pvalues=\(pStr)"
        }
        let cmd = AVCommand(relativeUrl: url, method: "GET", data: nil, app: nil)
        return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Array<TEntity> in
            var body = (avResponse.jsonBody)!
            let results = body["results"] as! Array<Any>
            return results.map({ (item) -> TEntity in
                let jsonResult = item as! [String: Any]
                let state = AVCorePlugins.sharedInstance.objectDecoder.decode(serverResult: jsonResult, decoder: AVCorePlugins.sharedInstance.avDecoder)
                return TEntity(serverState: state)
            })
        })
    }
}
 | 
	mit | 
| 
	larryhou/swift | 
	VideoDecode/ScreenRecordingTests/ScreenRecordingTests.swift | 
	1 | 
	978 | 
	//
//  ScreenRecordingTests.swift
//  ScreenRecordingTests
//
//  Created by larryhou on 14/01/2018.
//  Copyright © 2018 larryhou. All rights reserved.
//
import XCTest
@testable import ScreenRecording
class ScreenRecordingTests: XCTestCase {
    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    func testExample() {
        // This is an example of a functional test case.
        // Use XCTAssert and related functions to verify your tests produce the correct results.
    }
    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measure {
            // Put the code you want to measure the time of here.
        }
    }
}
 | 
	mit | 
| 
	lucas34/SwiftQueue | 
	Tests/LinuxMain.swift | 
	1 | 
	125 | 
	import XCTest
import SwiftQueueTests
var tests = [XCTestCaseEntry]()
tests += SwiftQueueTests.__allTests()
XCTMain(tests)
 | 
	mit | 
| 
	dclelland/GridSpan | 
	GridSpan.swift | 
	1 | 
	3194 | 
	//
//  GridSpan.swift
//  Pods
//
//  Created by Daniel Clelland on 11/03/17.
//
import UIKit
/// A span object representing a rectangular range of cells in a grid.
public struct Span {
    
    /// A closed range of columns in the grid.
    /// For example, a value of `0...0` would indicate just the first column.
    public var columns: ClosedRange<Int>
    
    /// A closed range of rows in the grid.
    /// For example, a value of `0...0` would indicate just the first row.
    public var rows: ClosedRange<Int>
    
    /// Initialize the span with two ranges.
    public init(columns: ClosedRange<Int>, rows: ClosedRange<Int>) {
        self.columns = columns
        self.rows = rows
    }
    
    /// Convenience initializer for initializing the span with for separate components, not unlike CGRect's primary initializer.
    public init(column: Int, row: Int, columns: Int = 1, rows: Int = 1) {
        self.init(
            columns: column...(column + columns - 1),
            rows: row...(row + rows - 1)
        )
    }
    
}
/// A grid struct used to create CGRects aligned to a pixel grid with gutter.
public struct Grid {
    
    /// The grid's number of columns.
    public var columns: Int
    
    /// The grid's number of rows.
    public var rows: Int
    
    /// The grid's bounds: the frame of reference for all calculations.
    public var bounds: CGRect
    
    /// The grid's gutter: defines the spacing between cells on the grid.
    public var gutter: CGSize
    
    /// Initializes a grid with columns, rows, bounds, and a default gutter.
    public init(columns: Int, rows: Int, bounds: CGRect, gutter: CGSize = .zero) {
        self.columns = columns
        self.rows = rows
        self.bounds = bounds
        self.gutter = gutter
    }
    
    /// Calculates a rect for a given span on the grid.
    /// Rects are aligned to a pixel scale which rounds the output value so that a constant gutter is displayed.
    ///
    /// The pixel scale defaults to `UIScreen.main.scale`.
    public func bounds(for span: Span, scale: CGFloat = UIScreen.main.scale) -> CGRect {
        let width = (gutter.width + bounds.width) / CGFloat(columns)
        let height = (gutter.height + bounds.height) / CGFloat(rows)
        
        let left = round((CGFloat(span.columns.lowerBound) * width + bounds.minX) * scale) / scale;
        let top = round((CGFloat(span.rows.lowerBound) * height + bounds.minY) * scale) / scale;
        
        let right = round((CGFloat(span.columns.upperBound + 1) * width + bounds.minX - gutter.width) * scale) / scale;
        let bottom = round((CGFloat(span.rows.upperBound + 1) * height + bounds.minY - gutter.height) * scale) / scale;
        
        return CGRect(x: left, y: top, width: right - left, height: bottom - top)
    }
    
    /// Calculates the rect for a given index in the grid, reading left to right and top to bottom.
    ///
    /// For example, index 6 on a 4 by 4 grid means the cell at column 2, row 1.
    public func bounds(for index: Int, scale: CGFloat = UIScreen.main.scale) -> CGRect {
        return bounds(for: Span(column: index % columns, row: index / columns), scale: scale)
    }
    
}
 | 
	mit | 
| 
	Johennes/firefox-ios | 
	Sync/EncryptedJSON.swift | 
	2 | 
	3231 | 
	/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import FxA
import Account
import XCGLogger
private let log = Logger.syncLogger
/**
 * Turns JSON of the form
 *
 *  { ciphertext: ..., hmac: ..., iv: ...}
 *
 * into a new JSON object resulting from decrypting and parsing the ciphertext.
 */
public class EncryptedJSON: JSON {
    var _cleartext: JSON?               // Cache decrypted cleartext.
    var _ciphertextBytes: NSData?       // Cache decoded ciphertext.
    var _hmacBytes: NSData?             // Cache decoded HMAC.
    var _ivBytes: NSData?               // Cache decoded IV.
    var valid: Bool = false
    var validated: Bool = false
    let keyBundle: KeyBundle
    public init(json: String, keyBundle: KeyBundle) {
        self.keyBundle = keyBundle
        super.init(JSON.parse(json))
    }
    public init(json: JSON, keyBundle: KeyBundle) {
        self.keyBundle = keyBundle
        super.init(json)
    }
    private func validate() -> Bool {
        if validated {
            return valid
        }
        valid = self["ciphertext"].isString &&
            self["hmac"].isString &&
            self["IV"].isString
        if (!valid) {
            validated = true
            return false
        }
        validated = true
        if let ciphertextForHMAC = self.ciphertextB64 {
            return keyBundle.verify(hmac: self.hmac, ciphertextB64: ciphertextForHMAC)
        } else {
            return false
        }
    }
    public func isValid() -> Bool {
        return !isError &&
            self.validate()
    }
    func fromBase64(str: String) -> NSData {
        let b = Bytes.decodeBase64(str)
        return b
    }
    var ciphertextB64: NSData? {
        if let ct = self["ciphertext"].asString {
            return Bytes.dataFromBase64(ct)
        } else {
            return nil
        }
    }
    var ciphertext: NSData {
        if (_ciphertextBytes != nil) {
            return _ciphertextBytes!
        }
        _ciphertextBytes = fromBase64(self["ciphertext"].asString!)
        return _ciphertextBytes!
    }
    var hmac: NSData {
        if (_hmacBytes != nil) {
            return _hmacBytes!
        }
        _hmacBytes = NSData(base16EncodedString: self["hmac"].asString!, options: NSDataBase16DecodingOptions.Default)
        return _hmacBytes!
    }
    var iv: NSData {
        if (_ivBytes != nil) {
            return _ivBytes!
        }
        _ivBytes = fromBase64(self["IV"].asString!)
        return _ivBytes!
    }
    // Returns nil on error.
    public var cleartext: JSON? {
        if (_cleartext != nil) {
            return _cleartext
        }
        if (!validate()) {
            log.error("Failed to validate.")
            return nil
        }
        let decrypted: String? = keyBundle.decrypt(self.ciphertext, iv: self.iv)
        if (decrypted == nil) {
            log.error("Failed to decrypt.")
            valid = false
            return nil
        }
        _cleartext = JSON.parse(decrypted!)
        return _cleartext!
    }
} | 
	mpl-2.0 | 
			Subsets and Splits
				
	
				
			
				
No community queries yet
The top public SQL queries from the community will appear here once available.