diff --git a/README.md b/README.md
index ddf8548b052a..0f3d6f4452f9 100644
--- a/README.md
+++ b/README.md
@@ -1049,6 +1049,7 @@ Here is a list of template creators:
* Swift 3: @hexelon
* Swift 4: @ehyche
* Swift 5: @4brunu
+ * Swift 6: @4brunu
* Swift Combine: @dydus0x14
* TypeScript (Angular1): @mhardorf
* TypeScript (Angular2): @roni-frantchi
diff --git a/bin/configs/swift6-alamofireLibrary.yaml b/bin/configs/swift6-alamofireLibrary.yaml
new file mode 100644
index 000000000000..c4b453e9bf55
--- /dev/null
+++ b/bin/configs/swift6-alamofireLibrary.yaml
@@ -0,0 +1,12 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/alamofireLibrary
+library: alamofire
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+useCustomDateWithoutTime: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-any-codable.yaml b/bin/configs/swift6-any-codable.yaml
new file mode 100644
index 000000000000..2092fd47605f
--- /dev/null
+++ b/bin/configs/swift6-any-codable.yaml
@@ -0,0 +1,10 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/anycodableLibrary
+inputSpec: modules/openapi-generator/src/test/resources/3_0/any_codable.yaml
+modelNamePrefix: Prefix
+modelNameSuffix: Suffix
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-api-non-static-method.yaml b/bin/configs/swift6-api-non-static-method.yaml
new file mode 100644
index 000000000000..b09a558c0d9f
--- /dev/null
+++ b/bin/configs/swift6-api-non-static-method.yaml
@@ -0,0 +1,12 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/apiNonStaticMethod
+library: alamofire
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+additionalProperties:
+ responseAs: AsyncAwait,Combine,Result,PromiseKit,RxSwift
+ apiStaticMethod: false
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-asyncAwaitLibrary.yaml b/bin/configs/swift6-asyncAwaitLibrary.yaml
new file mode 100644
index 000000000000..627cacde3bb7
--- /dev/null
+++ b/bin/configs/swift6-asyncAwaitLibrary.yaml
@@ -0,0 +1,11 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/asyncAwaitLibrary
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ responseAs: AsyncAwait
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-combineDeferredLibrary.yaml b/bin/configs/swift6-combineDeferredLibrary.yaml
new file mode 100644
index 000000000000..7496bc505b0c
--- /dev/null
+++ b/bin/configs/swift6-combineDeferredLibrary.yaml
@@ -0,0 +1,11 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/combineDeferredLibrary
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ responseAs: Combine
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-combineLibrary.yaml b/bin/configs/swift6-combineLibrary.yaml
new file mode 100644
index 000000000000..955fd6eeaa1f
--- /dev/null
+++ b/bin/configs/swift6-combineLibrary.yaml
@@ -0,0 +1,12 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/combineLibrary
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ responseAs: Combine
+ combineDeferred: false
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-default.yaml b/bin/configs/swift6-default.yaml
new file mode 100644
index 000000000000..eef77e89b249
--- /dev/null
+++ b/bin/configs/swift6-default.yaml
@@ -0,0 +1,12 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/default
+inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
+enumNameMappings:
+ delivered: shipped
diff --git a/bin/configs/swift6-deprecated.yaml b/bin/configs/swift6-deprecated.yaml
new file mode 100644
index 000000000000..f48b94637416
--- /dev/null
+++ b/bin/configs/swift6-deprecated.yaml
@@ -0,0 +1,10 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/deprecated
+inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-deprecated-fields.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-frozenEnums.yaml b/bin/configs/swift6-frozenEnums.yaml
new file mode 100644
index 000000000000..4bcc2eb8c74b
--- /dev/null
+++ b/bin/configs/swift6-frozenEnums.yaml
@@ -0,0 +1,12 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/frozenEnums
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ sortParamsByRequiredFlag: false
+ enumUnknownDefaultCase: true
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-nonPublicApi.yaml b/bin/configs/swift6-nonPublicApi.yaml
new file mode 100644
index 000000000000..33f01a77c3f4
--- /dev/null
+++ b/bin/configs/swift6-nonPublicApi.yaml
@@ -0,0 +1,21 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/nonPublicApi
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ sortParamsByRequiredFlag: false
+ nonPublicApi: true
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
+nameMappings:
+ _type: underscoreType
+ type_: typeWithUnderscore
+ -type: dashType
+parameterNameMappings:
+ _type: underscoreType
+ type_: typeWithUnderscore
+ -type: dashType
+
diff --git a/bin/configs/swift6-objcCompatible.yaml b/bin/configs/swift6-objcCompatible.yaml
new file mode 100644
index 000000000000..f86f676429e0
--- /dev/null
+++ b/bin/configs/swift6-objcCompatible.yaml
@@ -0,0 +1,11 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/objcCompatible
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ objcCompatible: true
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-oneOf.yaml b/bin/configs/swift6-oneOf.yaml
new file mode 100644
index 000000000000..a5df35f81542
--- /dev/null
+++ b/bin/configs/swift6-oneOf.yaml
@@ -0,0 +1,10 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/oneOf
+inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOf.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-promisekitLibrary.yaml b/bin/configs/swift6-promisekitLibrary.yaml
new file mode 100644
index 000000000000..5634bd902b46
--- /dev/null
+++ b/bin/configs/swift6-promisekitLibrary.yaml
@@ -0,0 +1,11 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/promisekitLibrary
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ responseAs: PromiseKit
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-readonlyProperties.yaml b/bin/configs/swift6-readonlyProperties.yaml
new file mode 100644
index 000000000000..251e1d9971b0
--- /dev/null
+++ b/bin/configs/swift6-readonlyProperties.yaml
@@ -0,0 +1,11 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/readonlyProperties
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ readonlyProperties: true
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-resultLibrary.yaml b/bin/configs/swift6-resultLibrary.yaml
new file mode 100644
index 000000000000..96a425c054f0
--- /dev/null
+++ b/bin/configs/swift6-resultLibrary.yaml
@@ -0,0 +1,11 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/resultLibrary
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ responseAs: Result
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-rxswiftLibrary.yaml b/bin/configs/swift6-rxswiftLibrary.yaml
new file mode 100644
index 000000000000..8221669ca6aa
--- /dev/null
+++ b/bin/configs/swift6-rxswiftLibrary.yaml
@@ -0,0 +1,13 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/rxswiftLibrary
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ responseAs: RxSwift
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
+ useBacktickEscapes: true
+ generateModelAdditionalProperties: false
diff --git a/bin/configs/swift6-urlsessionLibrary.yaml b/bin/configs/swift6-urlsessionLibrary.yaml
new file mode 100644
index 000000000000..c360c4bc730d
--- /dev/null
+++ b/bin/configs/swift6-urlsessionLibrary.yaml
@@ -0,0 +1,14 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/urlsessionLibrary
+library: urlsession
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
+ useSPMFileStructure: true
+ useClasses: true
+ swiftUseApiNamespace: true
diff --git a/bin/configs/swift6-validation.yaml b/bin/configs/swift6-validation.yaml
new file mode 100644
index 000000000000..0eec4f88675b
--- /dev/null
+++ b/bin/configs/swift6-validation.yaml
@@ -0,0 +1,10 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/validation
+inputSpec: modules/openapi-generator/src/test/resources/3_0/validation.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
diff --git a/bin/configs/swift6-vapor.yaml b/bin/configs/swift6-vapor.yaml
new file mode 100644
index 000000000000..948e4c7429fd
--- /dev/null
+++ b/bin/configs/swift6-vapor.yaml
@@ -0,0 +1,12 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/vaporLibrary
+library: vapor
+inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ projectName: PetstoreClient
+ useSPMFileStructure: true
+ useClasses: true
+ useBacktickEscapes: true
+ mapFileBinaryToData: true
diff --git a/bin/configs/swift6-x-swift-hashable.yaml b/bin/configs/swift6-x-swift-hashable.yaml
new file mode 100644
index 000000000000..63760de67d64
--- /dev/null
+++ b/bin/configs/swift6-x-swift-hashable.yaml
@@ -0,0 +1,11 @@
+generatorName: swift6
+outputDir: samples/client/petstore/swift6/x-swift-hashable
+inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml
+templateDir: modules/openapi-generator/src/main/resources/swift6
+generateAliasAsModel: true
+additionalProperties:
+ podAuthors: ""
+ podSummary: PetstoreClient
+ projectName: PetstoreClient
+ podHomepage: https://github.com/openapitools/openapi-generator
+ hashableModels: false
diff --git a/bitrise.yml b/bitrise.yml
index 290f77635082..69390c39ae63 100644
--- a/bitrise.yml
+++ b/bitrise.yml
@@ -18,6 +18,15 @@ workflows:
#!/usr/bin/env bash
sudo gem install cocoapods
+ - script@1.2.0:
+ title: Run Swift6 tests
+ inputs:
+ - content: |
+ #!/usr/bin/env bash
+
+ set -e
+
+ ./samples/client/petstore/swift6/swift6_test_all.sh
- script@1.2.0:
title: Run Swift5 tests
inputs:
@@ -39,4 +48,4 @@ workflows:
meta:
bitrise.io:
- stack: osx-xcode-14.3.x-ventura
+ stack: osx-xcode-16.0.x
diff --git a/docs/generators.md b/docs/generators.md
index 6cf92be19458..4d7c4e45ce40 100644
--- a/docs/generators.md
+++ b/docs/generators.md
@@ -65,6 +65,7 @@ The following generators are available:
* [scalaz](generators/scalaz.md)
* [swift-combine](generators/swift-combine.md)
* [swift5](generators/swift5.md)
+* [swift6 (experimental)](generators/swift6.md)
* [typescript (experimental)](generators/typescript.md)
* [typescript-angular](generators/typescript-angular.md)
* [typescript-aurelia](generators/typescript-aurelia.md)
diff --git a/docs/generators/swift6.md b/docs/generators/swift6.md
new file mode 100644
index 000000000000..955e74b87d48
--- /dev/null
+++ b/docs/generators/swift6.md
@@ -0,0 +1,358 @@
+---
+title: Documentation for the swift6 Generator
+---
+
+## METADATA
+
+| Property | Value | Notes |
+| -------- | ----- | ----- |
+| generator name | swift6 | pass this to the generate command after -g |
+| generator stability | EXPERIMENTAL | |
+| generator type | CLIENT | |
+| generator language | Swift | |
+| generator default templating engine | mustache | |
+| helpTxt | Generates a Swift 6.x client library. | |
+
+## CONFIG OPTIONS
+These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details.
+
+| Option | Description | Values | Default |
+| ------ | ----------- | ------ | ------- |
+|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false|
+|apiNamePrefix|Prefix that will be appended to all API names ('tags'). Default: empty string. e.g. Pet => Pet.| |null|
+|apiStaticMethod|Make api calls using a static method (default: true)| |true|
+|combineDeferred|Make combine usages deferred (default: true)| |true|
+|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
- **false**
- The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
- **true**
- Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
|true|
+|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true|
+|enumUnknownDefaultCase|If the server adds new enum cases, that are unknown by an old spec/client, the client will fail to parse the network response.With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the server sends an enum case that is not known by the client/spec, they can safely fallback to this case.|- **false**
- No changes to the enum's are made, this is the default option.
- **true**
- With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
|false|
+|generateModelAdditionalProperties|Generate model additional properties (default: true)| |true|
+|hashableModels|Make hashable models (default: true)| |true|
+|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true|
+|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|- **true**
- The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
- **false**
- The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true|
+|lenientTypeCast|Accept and cast values for simple types (string->bool, string->int, int->string)| |false|
+|library|Library template (sub-template) to use|- **urlsession**
- [DEFAULT] HTTP client: URLSession
- **alamofire**
- HTTP client: Alamofire
- **vapor**
- HTTP client: Vapor
|urlsession|
+|mapFileBinaryToData|[WARNING] This option will be removed and enabled by default in the future once we've enhanced the code to work with `Data` in all the different situations. Map File and Binary to Data (default: false)| |false|
+|nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.(default: false)| |null|
+|objcCompatible|Add additional properties and methods for Objective-C compatibility (default: false)| |null|
+|podAuthors|Authors used for Podspec| |null|
+|podDescription|Description used for Podspec| |null|
+|podDocumentationURL|Documentation URL used for Podspec| |null|
+|podHomepage|Homepage used for Podspec| |null|
+|podLicense|License used for Podspec| |null|
+|podScreenshots|Screenshots used for Podspec| |null|
+|podSocialMediaURL|Social Media URL used for Podspec| |null|
+|podSource|Source information used for Podspec| |null|
+|podSummary|Summary used for Podspec| |null|
+|podVersion|Version used for Podspec| |null|
+|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false|
+|projectName|Project name in Xcode| |null|
+|readonlyProperties|Make properties readonly (default: false)| |null|
+|responseAs|Optionally use libraries to manage response. Currently PromiseKit, RxSwift, Result, Combine, AsyncAwait are available.| |null|
+|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
+|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
+|swiftPackagePath|Set a custom source path instead of OpenAPIClient/Classes/OpenAPIs.| |null|
+|swiftUseApiNamespace|Flag to make all the API classes inner-class of {{projectName}}API| |null|
+|useBacktickEscapes|Escape reserved words using backticks (default: false)| |false|
+|useClasses|Use final classes for models instead of structs (default: false)| |false|
+|useCustomDateWithoutTime|Uses a custom type to decode and encode dates without time information to support OpenAPIs date format (default: false)| |false|
+|useJsonEncodable|Make models conform to JSONEncodable protocol (default: true)| |true|
+|useSPMFileStructure|Use SPM file structure and set the source path to Sources/{{projectName}} (default: false).| |null|
+|validatable|Make validation rules and validator for model properies (default: true)| |true|
+
+## IMPORT MAPPING
+
+| Type/Alias | Imports |
+| ---------- | ------- |
+
+
+## INSTANTIATION TYPES
+
+| Type/Alias | Instantiated By |
+| ---------- | --------------- |
+
+
+## LANGUAGE PRIMITIVES
+
+
+- Any
+- AnyCodable
+- AnyObject
+- Bool
+- Character
+- Data
+- Date
+- Decimal
+- Double
+- Float
+- Int
+- Int32
+- Int64
+- OpenAPIDateWithoutTime
+- String
+- URL
+- UUID
+- Void
+
+
+## RESERVED WORDS
+
+
+- #available
+- #colorLiteral
+- #column
+- #else
+- #elseif
+- #endif
+- #file
+- #fileLiteral
+- #function
+- #if
+- #imageLiteral
+- #line
+- #selector
+- #sourceLocation
+- Any
+- AnyObject
+- Array
+- Bool
+- COLUMN
+- Character
+- Class
+- ClosedRange
+- Codable
+- CountableClosedRange
+- CountableRange
+- Data
+- Decodable
+- Dictionary
+- Double
+- Encodable
+- Error
+- ErrorResponse
+- FILE
+- FUNCTION
+- Float
+- Float32
+- Float64
+- Float80
+- Int
+- Int16
+- Int32
+- Int64
+- Int8
+- LINE
+- OptionSet
+- Optional
+- Protocol
+- Range
+- Response
+- Self
+- Set
+- StaticString
+- String
+- Type
+- UInt
+- UInt16
+- UInt32
+- UInt64
+- UInt8
+- URL
+- Unicode
+- Void
+- _
+- as
+- associatedtype
+- associativity
+- break
+- case
+- catch
+- class
+- continue
+- convenience
+- default
+- defer
+- deinit
+- didSet
+- do
+- dynamic
+- dynamicType
+- else
+- enum
+- extension
+- fallthrough
+- false
+- fileprivate
+- final
+- for
+- func
+- get
+- guard
+- if
+- import
+- in
+- indirect
+- infix
+- init
+- inout
+- internal
+- is
+- lazy
+- left
+- let
+- mutating
+- nil
+- none
+- nonmutating
+- open
+- operator
+- optional
+- override
+- postfix
+- precedence
+- prefix
+- private
+- protocol
+- public
+- repeat
+- required
+- rethrows
+- return
+- right
+- self
+- set
+- static
+- struct
+- subscript
+- super
+- switch
+- throw
+- throws
+- true
+- try
+- typealias
+- unowned
+- var
+- weak
+- where
+- while
+- willSet
+
+
+## FEATURE SET
+
+
+### Client Modification Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|BasePath|✗|ToolingExtension
+|Authorizations|✗|ToolingExtension
+|UserAgent|✗|ToolingExtension
+|MockServer|✗|ToolingExtension
+
+### Data Type Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Custom|✗|OAS2,OAS3
+|Int32|✓|OAS2,OAS3
+|Int64|✓|OAS2,OAS3
+|Float|✓|OAS2,OAS3
+|Double|✓|OAS2,OAS3
+|Decimal|✓|ToolingExtension
+|String|✓|OAS2,OAS3
+|Byte|✓|OAS2,OAS3
+|Binary|✓|OAS2,OAS3
+|Boolean|✓|OAS2,OAS3
+|Date|✓|OAS2,OAS3
+|DateTime|✓|OAS2,OAS3
+|Password|✓|OAS2,OAS3
+|File|✓|OAS2
+|Uuid|✗|
+|Array|✓|OAS2,OAS3
+|Null|✗|OAS3
+|AnyType|✗|OAS2,OAS3
+|Object|✓|OAS2,OAS3
+|Maps|✓|ToolingExtension
+|CollectionFormat|✓|OAS2
+|CollectionFormatMulti|✓|OAS2
+|Enum|✓|OAS2,OAS3
+|ArrayOfEnum|✓|ToolingExtension
+|ArrayOfModel|✓|ToolingExtension
+|ArrayOfCollectionOfPrimitives|✓|ToolingExtension
+|ArrayOfCollectionOfModel|✓|ToolingExtension
+|ArrayOfCollectionOfEnum|✓|ToolingExtension
+|MapOfEnum|✓|ToolingExtension
+|MapOfModel|✓|ToolingExtension
+|MapOfCollectionOfPrimitives|✓|ToolingExtension
+|MapOfCollectionOfModel|✓|ToolingExtension
+|MapOfCollectionOfEnum|✓|ToolingExtension
+
+### Documentation Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Readme|✗|ToolingExtension
+|Model|✓|ToolingExtension
+|Api|✓|ToolingExtension
+
+### Global Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Host|✓|OAS2,OAS3
+|BasePath|✓|OAS2,OAS3
+|Info|✓|OAS2,OAS3
+|Schemes|✗|OAS2,OAS3
+|PartialSchemes|✓|OAS2,OAS3
+|Consumes|✓|OAS2
+|Produces|✓|OAS2
+|ExternalDocumentation|✓|OAS2,OAS3
+|Examples|✓|OAS2,OAS3
+|XMLStructureDefinitions|✗|OAS2,OAS3
+|MultiServer|✗|OAS3
+|ParameterizedServer|✗|OAS3
+|ParameterStyling|✗|OAS3
+|Callbacks|✓|OAS3
+|LinkObjects|✗|OAS3
+
+### Parameter Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Path|✓|OAS2,OAS3
+|Query|✓|OAS2,OAS3
+|Header|✓|OAS2,OAS3
+|Body|✓|OAS2
+|FormUnencoded|✓|OAS2
+|FormMultipart|✓|OAS2
+|Cookie|✓|OAS3
+
+### Schema Support Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|Simple|✓|OAS2,OAS3
+|Composite|✓|OAS2,OAS3
+|Polymorphism|✓|OAS2,OAS3
+|Union|✗|OAS3
+|allOf|✗|OAS2,OAS3
+|anyOf|✗|OAS3
+|oneOf|✗|OAS3
+|not|✗|OAS3
+
+### Security Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|BasicAuth|✓|OAS2,OAS3
+|ApiKey|✓|OAS2,OAS3
+|OpenIDConnect|✗|OAS3
+|BearerToken|✓|OAS3
+|OAuth2_Implicit|✓|OAS2,OAS3
+|OAuth2_Password|✓|OAS2,OAS3
+|OAuth2_ClientCredentials|✓|OAS2,OAS3
+|OAuth2_AuthorizationCode|✓|OAS2,OAS3
+|SignatureAuth|✗|OAS3
+|AWSV4Signature|✗|ToolingExtension
+
+### Wire Format Feature
+| Name | Supported | Defined By |
+| ---- | --------- | ---------- |
+|JSON|✓|OAS2,OAS3
+|XML|✓|OAS2,OAS3
+|PROTOBUF|✗|ToolingExtension
+|Custom|✗|OAS2,OAS3
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift6ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift6ClientCodegen.java
new file mode 100644
index 000000000000..e9b5023c1c55
--- /dev/null
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift6ClientCodegen.java
@@ -0,0 +1,1387 @@
+/*
+ * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
+ * Copyright 2018 SmartBear Software
+ *
+ * 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
+ *
+ * https://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.
+ */
+
+package org.openapitools.codegen.languages;
+
+import io.swagger.v3.oas.models.media.Schema;
+import lombok.Getter;
+import lombok.Setter;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.text.WordUtils;
+import org.openapitools.codegen.*;
+import org.openapitools.codegen.meta.GeneratorMetadata;
+import org.openapitools.codegen.meta.Stability;
+import org.openapitools.codegen.model.ModelMap;
+import org.openapitools.codegen.model.ModelsMap;
+import org.openapitools.codegen.model.OperationMap;
+import org.openapitools.codegen.model.OperationsMap;
+import org.openapitools.codegen.utils.ModelUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.*;
+import java.time.OffsetDateTime;
+import java.time.Instant;
+import java.time.temporal.ChronoField;
+import java.util.concurrent.TimeUnit;
+
+import static org.openapitools.codegen.utils.CamelizeOption.LOWERCASE_FIRST_LETTER;
+import static org.openapitools.codegen.utils.StringUtils.camelize;
+
+public class Swift6ClientCodegen extends DefaultCodegen implements CodegenConfig {
+ private final Logger LOGGER = LoggerFactory.getLogger(Swift6ClientCodegen.class);
+
+ public static final String PROJECT_NAME = "projectName";
+ public static final String RESPONSE_AS = "responseAs";
+ public static final String OBJC_COMPATIBLE = "objcCompatible";
+ public static final String POD_SOURCE = "podSource";
+ public static final String POD_AUTHORS = "podAuthors";
+ public static final String POD_SOCIAL_MEDIA_URL = "podSocialMediaURL";
+ public static final String POD_LICENSE = "podLicense";
+ public static final String POD_HOMEPAGE = "podHomepage";
+ public static final String POD_SUMMARY = "podSummary";
+ public static final String POD_DESCRIPTION = "podDescription";
+ public static final String POD_SCREENSHOTS = "podScreenshots";
+ public static final String POD_DOCUMENTATION_URL = "podDocumentationURL";
+ public static final String READONLY_PROPERTIES = "readonlyProperties";
+ public static final String SWIFT_USE_API_NAMESPACE = "swiftUseApiNamespace";
+ public static final String DEFAULT_POD_AUTHORS = "OpenAPI Generator";
+ public static final String LENIENT_TYPE_CAST = "lenientTypeCast";
+ public static final String USE_SPM_FILE_STRUCTURE = "useSPMFileStructure";
+ public static final String SWIFT_PACKAGE_PATH = "swiftPackagePath";
+ public static final String USE_CLASSES = "useClasses";
+ public static final String USE_BACKTICK_ESCAPES = "useBacktickEscapes";
+ public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES = "generateModelAdditionalProperties";
+ public static final String HASHABLE_MODELS = "hashableModels";
+ public static final String USE_JSON_ENCODABLE = "useJsonEncodable";
+ public static final String MAP_FILE_BINARY_TO_DATA = "mapFileBinaryToData";
+ public static final String USE_CUSTOM_DATE_WITHOUT_TIME = "useCustomDateWithoutTime";
+ public static final String VALIDATABLE = "validatable";
+ public static final String API_STATIC_METHOD = "apiStaticMethod";
+ public static final String COMBINE_DEFERRED = "combineDeferred";
+ protected static final String LIBRARY_ALAMOFIRE = "alamofire";
+ protected static final String LIBRARY_URLSESSION = "urlsession";
+ protected static final String LIBRARY_VAPOR = "vapor";
+ protected static final String RESPONSE_LIBRARY_PROMISE_KIT = "PromiseKit";
+ protected static final String RESPONSE_LIBRARY_RX_SWIFT = "RxSwift";
+ protected static final String RESPONSE_LIBRARY_RESULT = "Result";
+ protected static final String RESPONSE_LIBRARY_COMBINE = "Combine";
+ protected static final String RESPONSE_LIBRARY_ASYNC_AWAIT = "AsyncAwait";
+ protected static final String[] RESPONSE_LIBRARIES = { RESPONSE_LIBRARY_PROMISE_KIT, RESPONSE_LIBRARY_RX_SWIFT,
+ RESPONSE_LIBRARY_RESULT, RESPONSE_LIBRARY_COMBINE, RESPONSE_LIBRARY_ASYNC_AWAIT };
+ @Setter
+ protected String projectName = "OpenAPIClient";
+ @Setter
+ protected boolean nonPublicApi = false;
+ @Setter
+ protected boolean objcCompatible = false;
+ @Setter
+ protected boolean lenientTypeCast = false;
+ @Setter
+ protected boolean readonlyProperties = false;
+ @Setter
+ protected boolean swiftUseApiNamespace = false;
+ @Setter
+ protected boolean useSPMFileStructure = false;
+ @Setter
+ protected String swiftPackagePath = "Classes" + File.separator + "OpenAPIs";
+ @Setter
+ protected boolean useClasses = false;
+ @Setter
+ protected boolean useBacktickEscapes = false;
+ @Setter
+ protected boolean generateModelAdditionalProperties = true;
+ @Setter
+ protected boolean hashableModels = true;
+ @Setter
+ protected boolean useJsonEncodable = true;
+ @Getter
+ @Setter
+ protected boolean mapFileBinaryToData = false;
+ @Setter
+ protected boolean useCustomDateWithoutTime = false;
+ @Setter
+ protected boolean validatable = true;
+ @Setter
+ protected boolean apiStaticMethod = true;
+ @Setter
+ protected boolean combineDeferred = true;
+ @Setter
+ protected String[] responseAs = new String[0];
+ protected String sourceFolder = swiftPackagePath;
+ protected HashSet objcReservedWords;
+ protected String apiDocPath = "docs/";
+ protected String modelDocPath = "docs/";
+
+ /**
+ * Constructor for the swift6 language codegen module.
+ */
+ public Swift6ClientCodegen() {
+ super();
+ this.useOneOfInterfaces = true;
+
+ generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata)
+ .stability(Stability.EXPERIMENTAL)
+ .build();
+
+ outputFolder = "generated-code" + File.separator + "swift";
+ modelTemplateFiles.put("model.mustache", ".swift");
+ apiTemplateFiles.put("api.mustache", ".swift");
+ embeddedTemplateDir = templateDir = "swift6";
+ apiPackage = File.separator + "APIs";
+ modelPackage = File.separator + "Models";
+ modelDocTemplateFiles.put("model_doc.mustache", ".md");
+ apiDocTemplateFiles.put("api_doc.mustache", ".md");
+
+ languageSpecificPrimitives = new HashSet<>(
+ Arrays.asList(
+ "Int",
+ "Int32",
+ "Int64",
+ "Float",
+ "Double",
+ "Bool",
+ "Void",
+ "String",
+ "Data",
+ "Date",
+ "OpenAPIDateWithoutTime",
+ "Character",
+ "UUID",
+ "URL",
+ "AnyObject",
+ "Any",
+ "Decimal",
+ "AnyCodable") // from AnyCodable dependency
+ );
+ defaultIncludes = new HashSet<>(
+ Arrays.asList(
+ "Data",
+ "Date",
+ "URL", // for file
+ "UUID",
+ "Array",
+ "Dictionary",
+ "Set",
+ "Any",
+ "Empty",
+ "AnyObject",
+ "Any",
+ "Decimal"));
+
+ objcReservedWords = new HashSet<>(
+ Arrays.asList(
+ // Added for Objective-C compatibility
+ "id", "description", "NSArray", "NSURL", "CGFloat", "NSSet", "NSString", "NSInteger",
+ "NSUInteger",
+ "NSError", "NSDictionary",
+ // 'Property 'hash' with type 'String' cannot override a property with type
+ // 'Int' (when objcCompatible=true)
+ "hash",
+ // Cannot override with a stored property 'className'
+ "className"));
+
+ reservedWords = new HashSet<>(
+ Arrays.asList(
+ // name used by swift client
+ "ErrorResponse", "Response",
+
+ // Swift keywords. This list is taken from here:
+ // https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/doc/uid/TP40014097-CH30-ID410
+ //
+ // Keywords used in declarations
+ "associatedtype", "class", "deinit", "enum", "extension", "fileprivate", "func", "import",
+ "init",
+ "inout", "internal", "let", "open", "operator", "private", "protocol", "public", "static",
+ "struct",
+ "subscript", "typealias", "var",
+ // Keywords uses in statements
+ "break", "case", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard",
+ "if",
+ "in", "repeat", "return", "switch", "where", "while",
+ // Keywords used in expressions and types
+ "as", "Any", "catch", "false", "is", "nil", "rethrows", "super", "self", "Self", "throw",
+ "throws", "true", "try",
+ // Keywords used in patterns
+ "_",
+ // Keywords that begin with a number sign
+ "#available", "#colorLiteral", "#column", "#else", "#elseif", "#endif", "#file", "#fileLiteral",
+ "#function", "#if",
+ "#imageLiteral", "#line", "#selector", "#sourceLocation",
+ // Keywords reserved in particular contexts
+ "associativity", "convenience", "dynamic", "didSet", "final", "get", "infix", "indirect",
+ "lazy", "left",
+ "mutating", "none", "nonmutating", "optional", "override", "postfix", "precedence", "prefix",
+ "Protocol",
+ "required", "right", "set", "Type", "unowned", "weak", "willSet",
+
+ //
+ // Swift Standard Library types
+ // https://developer.apple.com/documentation/swift
+ //
+ // Numbers and Basic Values
+ "Bool", "Int", "Double", "Float", "Range", "ClosedRange", "Error", "Optional",
+ // Special-Use Numeric Types
+ "UInt", "UInt8", "UInt16", "UInt32", "UInt64", "Int8", "Int16", "Int32", "Int64", "Float80",
+ "Float32", "Float64",
+ // Strings and Text
+ "String", "Character", "Unicode", "StaticString",
+ // Collections
+ "Array", "Dictionary", "Set", "OptionSet", "CountableRange", "CountableClosedRange",
+
+ // The following are commonly-used Foundation types
+ "URL", "Data", "Codable", "Encodable", "Decodable",
+
+ // The following are other words we want to reserve
+ "Void", "AnyObject", "Class", "dynamicType", "COLUMN", "FILE", "FUNCTION", "LINE"));
+
+ typeMapping = new HashMap<>();
+ typeMapping.put("array", "Array");
+ typeMapping.put("map", "Dictionary");
+ typeMapping.put("set", "Set");
+ typeMapping.put("Date", "Date");
+ typeMapping.put("DateTime", "Date");
+ typeMapping.put("boolean", "Bool");
+ typeMapping.put("string", "String");
+ typeMapping.put("char", "Character");
+ typeMapping.put("short", "Int");
+ typeMapping.put("int", "Int");
+ typeMapping.put("long", "Int64");
+ typeMapping.put("integer", "Int");
+ typeMapping.put("Integer", "Int");
+ typeMapping.put("float", "Float");
+ typeMapping.put("number", "Double");
+ typeMapping.put("double", "Double");
+ typeMapping.put("file", "URL");
+ typeMapping.put("binary", "URL");
+ typeMapping.put("ByteArray", "Data");
+ typeMapping.put("UUID", "UUID");
+ typeMapping.put("URI", "String");
+ typeMapping.put("decimal", "Decimal");
+ typeMapping.put("object", "AnyCodable");
+ typeMapping.put("AnyType", "AnyCodable");
+
+ importMapping = new HashMap<>();
+
+ cliOptions.add(new CliOption(PROJECT_NAME, "Project name in Xcode"));
+ cliOptions.add(new CliOption(RESPONSE_AS,
+ "Optionally use libraries to manage response. Currently "
+ + StringUtils.join(RESPONSE_LIBRARIES, ", ")
+ + " are available."));
+ cliOptions.add(new CliOption(CodegenConstants.NON_PUBLIC_API,
+ CodegenConstants.NON_PUBLIC_API_DESC
+ + "(default: false)"));
+ cliOptions.add(new CliOption(OBJC_COMPATIBLE,
+ "Add additional properties and methods for Objective-C "
+ + "compatibility (default: false)"));
+ cliOptions.add(new CliOption(POD_SOURCE, "Source information used for Podspec"));
+ cliOptions.add(new CliOption(CodegenConstants.POD_VERSION, "Version used for Podspec"));
+ cliOptions.add(new CliOption(POD_AUTHORS, "Authors used for Podspec"));
+ cliOptions.add(new CliOption(POD_SOCIAL_MEDIA_URL, "Social Media URL used for Podspec"));
+ cliOptions.add(new CliOption(POD_LICENSE, "License used for Podspec"));
+ cliOptions.add(new CliOption(POD_HOMEPAGE, "Homepage used for Podspec"));
+ cliOptions.add(new CliOption(POD_SUMMARY, "Summary used for Podspec"));
+ cliOptions.add(new CliOption(POD_DESCRIPTION, "Description used for Podspec"));
+ cliOptions.add(new CliOption(POD_SCREENSHOTS, "Screenshots used for Podspec"));
+ cliOptions.add(new CliOption(POD_DOCUMENTATION_URL,
+ "Documentation URL used for Podspec"));
+ cliOptions.add(new CliOption(READONLY_PROPERTIES, "Make properties "
+ + "readonly (default: false)"));
+ cliOptions.add(new CliOption(SWIFT_USE_API_NAMESPACE,
+ "Flag to make all the API classes inner-class "
+ + "of {{projectName}}API"));
+ cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP,
+ CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC)
+ .defaultValue(Boolean.TRUE.toString()));
+ cliOptions.add(new CliOption(LENIENT_TYPE_CAST,
+ "Accept and cast values for simple types (string->bool, "
+ + "string->int, int->string)")
+ .defaultValue(Boolean.FALSE.toString()));
+ cliOptions.add(new CliOption(USE_BACKTICK_ESCAPES,
+ "Escape reserved words using backticks (default: false)")
+ .defaultValue(Boolean.FALSE.toString()));
+ cliOptions.add(new CliOption(GENERATE_MODEL_ADDITIONAL_PROPERTIES,
+ "Generate model additional properties (default: true)")
+ .defaultValue(Boolean.TRUE.toString()));
+
+ cliOptions.add(new CliOption(CodegenConstants.API_NAME_PREFIX, CodegenConstants.API_NAME_PREFIX_DESC));
+ cliOptions.add(new CliOption(USE_SPM_FILE_STRUCTURE, "Use SPM file structure"
+ + " and set the source path to Sources" + File.separator + "{{projectName}} (default: false)."));
+ cliOptions.add(new CliOption(SWIFT_PACKAGE_PATH, "Set a custom source path instead of "
+ + projectName + File.separator + "Classes" + File.separator + "OpenAPIs" + "."));
+ cliOptions.add(new CliOption(USE_CLASSES, "Use final classes for models instead of structs (default: false)")
+ .defaultValue(Boolean.FALSE.toString()));
+
+ cliOptions.add(new CliOption(HASHABLE_MODELS,
+ "Make hashable models (default: true)")
+ .defaultValue(Boolean.TRUE.toString()));
+
+ cliOptions.add(new CliOption(USE_JSON_ENCODABLE,
+ "Make models conform to JSONEncodable protocol (default: true)")
+ .defaultValue(Boolean.TRUE.toString()));
+
+ cliOptions.add(new CliOption(MAP_FILE_BINARY_TO_DATA,
+ "[WARNING] This option will be removed and enabled by default in the future once we've enhanced the code to work with `Data` in all the different situations. Map File and Binary to Data (default: false)")
+ .defaultValue(Boolean.FALSE.toString()));
+
+ cliOptions.add(new CliOption(USE_CUSTOM_DATE_WITHOUT_TIME,
+ "Uses a custom type to decode and encode dates without time information to support OpenAPIs date format (default: false)")
+ .defaultValue(Boolean.FALSE.toString()));
+
+ cliOptions.add(new CliOption(VALIDATABLE,
+ "Make validation rules and validator for model properies (default: true)")
+ .defaultValue(Boolean.TRUE.toString()));
+
+ cliOptions.add(new CliOption(API_STATIC_METHOD,
+ "Make api calls using a static method (default: true)")
+ .defaultValue(Boolean.TRUE.toString()));
+
+ cliOptions.add(new CliOption(COMBINE_DEFERRED,
+ "Make combine usages deferred (default: true)")
+ .defaultValue(Boolean.TRUE.toString()));
+
+ supportedLibraries.put(LIBRARY_URLSESSION, "[DEFAULT] HTTP client: URLSession");
+ supportedLibraries.put(LIBRARY_ALAMOFIRE, "HTTP client: Alamofire");
+ supportedLibraries.put(LIBRARY_VAPOR, "HTTP client: Vapor");
+
+ CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "Library template (sub-template) to use");
+ libraryOption.setEnum(supportedLibraries);
+ libraryOption.setDefault(LIBRARY_URLSESSION);
+ cliOptions.add(libraryOption);
+ setLibrary(LIBRARY_URLSESSION);
+ }
+
+ private static CodegenModel reconcileProperties(CodegenModel codegenModel,
+ CodegenModel parentCodegenModel) {
+ // To support inheritance in this generator, we will analyze
+ // the parent and child models, look for properties that match, and remove
+ // them from the child models and leave them in the parent.
+ // Because the child models extend the parents, the properties
+ // will be available via the parent.
+
+ // Get the properties for the parent and child models
+ final List parentModelCodegenProperties = parentCodegenModel.vars;
+ List codegenProperties = codegenModel.vars;
+ codegenModel.allVars = new ArrayList(codegenProperties);
+ codegenModel.parentVars = parentCodegenModel.allVars;
+
+ // Iterate over all of the parent model properties
+ boolean removedChildProperty = false;
+
+ for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) {
+ // Now that we have found a prop in the parent class,
+ // and search the child class for the same prop.
+ Iterator iterator = codegenProperties.iterator();
+ while (iterator.hasNext()) {
+ CodegenProperty codegenProperty = iterator.next();
+ if (codegenProperty.baseName.equals(parentModelCodegenProperty.baseName)) {
+ // We found a property in the child class that is
+ // a duplicate of the one in the parent, so remove it.
+ iterator.remove();
+ removedChildProperty = true;
+ }
+ }
+ }
+
+ if (removedChildProperty) {
+ codegenModel.vars = codegenProperties;
+ }
+
+ return codegenModel;
+ }
+
+ @Override
+ public CodegenType getTag() {
+ return CodegenType.CLIENT;
+ }
+
+ @Override
+ public String getName() {
+ return "swift6";
+ }
+
+ @Override
+ public String getHelp() {
+ return "Generates a Swift 6.x client library.";
+ }
+
+ @Override
+ protected void addAdditionPropertiesToCodeGenModel(CodegenModel codegenModel,
+ Schema schema) {
+
+ final Schema additionalProperties = ModelUtils.getAdditionalProperties(schema);
+
+ if (additionalProperties != null) {
+ Schema inner = null;
+ if (ModelUtils.isArraySchema(schema)) {
+ inner = ModelUtils.getSchemaItems(schema);
+ } else if (ModelUtils.isMapSchema(schema)) {
+ inner = ModelUtils.getAdditionalProperties(schema);
+ }
+
+ codegenModel.additionalPropertiesType = inner != null ? getTypeDeclaration(inner)
+ : getSchemaType(additionalProperties);
+ }
+ }
+
+ @Override
+ public void processOpts() {
+ super.processOpts();
+
+ if (StringUtils.isEmpty(System.getenv("SWIFT_POST_PROCESS_FILE"))) {
+ LOGGER.info(
+ "Environment variable SWIFT_POST_PROCESS_FILE not defined so the Swift code may not be properly formatted. To define it, try 'export SWIFT_POST_PROCESS_FILE=/usr/local/bin/swiftformat' (Linux/Mac)");
+ LOGGER.info(
+ "NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` (--enable-post-process-file for CLI).");
+ }
+
+ // Setup project name
+ if (additionalProperties.containsKey(PROJECT_NAME)) {
+ setProjectName((String) additionalProperties.get(PROJECT_NAME));
+ } else {
+ additionalProperties.put(PROJECT_NAME, projectName);
+ }
+ sourceFolder = projectName + File.separator + sourceFolder;
+
+ // Setup nonPublicApi option, which generates code with reduced access
+ // modifiers; allows embedding elsewhere without exposing non-public API calls
+ // to consumers
+ if (additionalProperties.containsKey(CodegenConstants.NON_PUBLIC_API)) {
+ setNonPublicApi(convertPropertyToBooleanAndWriteBack(CodegenConstants.NON_PUBLIC_API));
+ }
+ additionalProperties.put(CodegenConstants.NON_PUBLIC_API, nonPublicApi);
+
+ // Setup objcCompatible option, which adds additional properties
+ // and methods for Objective-C compatibility
+ if (additionalProperties.containsKey(OBJC_COMPATIBLE)) {
+ setObjcCompatible(convertPropertyToBooleanAndWriteBack(OBJC_COMPATIBLE));
+ }
+ additionalProperties.put(OBJC_COMPATIBLE, objcCompatible);
+
+ // add objc reserved words
+ if (Boolean.TRUE.equals(objcCompatible)) {
+ reservedWords.addAll(objcReservedWords);
+ }
+
+ if (additionalProperties.containsKey(RESPONSE_AS)) {
+ Object responseAsObject = additionalProperties.get(RESPONSE_AS);
+ if (responseAsObject instanceof String) {
+ setResponseAs(((String) responseAsObject).split(","));
+ } else {
+ setResponseAs((String[]) responseAsObject);
+ }
+ }
+ additionalProperties.put(RESPONSE_AS, responseAs);
+ if (ArrayUtils.contains(responseAs, RESPONSE_LIBRARY_PROMISE_KIT)) {
+ additionalProperties.put("usePromiseKit", true);
+ }
+ if (ArrayUtils.contains(responseAs, RESPONSE_LIBRARY_RX_SWIFT)) {
+ additionalProperties.put("useRxSwift", true);
+ }
+ if (ArrayUtils.contains(responseAs, RESPONSE_LIBRARY_RESULT)) {
+ additionalProperties.put("useResult", true);
+ }
+ if (ArrayUtils.contains(responseAs, RESPONSE_LIBRARY_COMBINE)) {
+ additionalProperties.put("useCombine", true);
+ }
+ if (ArrayUtils.contains(responseAs, RESPONSE_LIBRARY_ASYNC_AWAIT)) {
+ additionalProperties.put("useAsyncAwait", true);
+ }
+
+ // Setup readonlyProperties option, which declares properties so they can only
+ // be set at initialization
+ if (additionalProperties.containsKey(READONLY_PROPERTIES)) {
+ setReadonlyProperties(convertPropertyToBooleanAndWriteBack(READONLY_PROPERTIES));
+ }
+ additionalProperties.put(READONLY_PROPERTIES, readonlyProperties);
+
+ // Setup swiftUseApiNamespace option, which makes all the API
+ // classes inner-class of {{projectName}}API
+ if (additionalProperties.containsKey(SWIFT_USE_API_NAMESPACE)) {
+ setSwiftUseApiNamespace(convertPropertyToBooleanAndWriteBack(SWIFT_USE_API_NAMESPACE));
+ }
+
+ if (!additionalProperties.containsKey(POD_AUTHORS)) {
+ additionalProperties.put(POD_AUTHORS, DEFAULT_POD_AUTHORS);
+ }
+
+ if (additionalProperties.containsKey(USE_SPM_FILE_STRUCTURE)) {
+ setUseSPMFileStructure(convertPropertyToBooleanAndWriteBack(USE_SPM_FILE_STRUCTURE));
+ sourceFolder = "Sources" + File.separator + projectName;
+ }
+
+ if (additionalProperties.containsKey(SWIFT_PACKAGE_PATH)
+ && ((String) additionalProperties.get(SWIFT_PACKAGE_PATH)).length() > 0) {
+ setSwiftPackagePath((String) additionalProperties.get(SWIFT_PACKAGE_PATH));
+ sourceFolder = swiftPackagePath;
+ }
+
+ if (additionalProperties.containsKey(USE_BACKTICK_ESCAPES)) {
+ setUseBacktickEscapes(convertPropertyToBooleanAndWriteBack(USE_BACKTICK_ESCAPES));
+ }
+
+ if (additionalProperties.containsKey(GENERATE_MODEL_ADDITIONAL_PROPERTIES)) {
+ setGenerateModelAdditionalProperties(
+ convertPropertyToBooleanAndWriteBack(GENERATE_MODEL_ADDITIONAL_PROPERTIES));
+ }
+ additionalProperties.put(GENERATE_MODEL_ADDITIONAL_PROPERTIES, generateModelAdditionalProperties);
+
+ if (additionalProperties.containsKey(HASHABLE_MODELS)) {
+ setHashableModels(convertPropertyToBooleanAndWriteBack(HASHABLE_MODELS));
+ }
+ additionalProperties.put(HASHABLE_MODELS, hashableModels);
+
+ if (additionalProperties.containsKey(USE_JSON_ENCODABLE)) {
+ setUseJsonEncodable(convertPropertyToBooleanAndWriteBack(USE_JSON_ENCODABLE));
+ }
+ additionalProperties.put(USE_JSON_ENCODABLE, useJsonEncodable);
+
+ if (additionalProperties.containsKey(MAP_FILE_BINARY_TO_DATA)) {
+ setMapFileBinaryToData(convertPropertyToBooleanAndWriteBack(MAP_FILE_BINARY_TO_DATA));
+ }
+ additionalProperties.put(MAP_FILE_BINARY_TO_DATA, mapFileBinaryToData);
+ if (mapFileBinaryToData) {
+ typeMapping.put("file", "Data");
+ typeMapping.put("binary", "Data");
+ }
+
+ if (additionalProperties.containsKey(USE_CUSTOM_DATE_WITHOUT_TIME)) {
+ setUseCustomDateWithoutTime(convertPropertyToBooleanAndWriteBack(USE_CUSTOM_DATE_WITHOUT_TIME));
+ }
+ additionalProperties.put(USE_CUSTOM_DATE_WITHOUT_TIME, useCustomDateWithoutTime);
+ if (useCustomDateWithoutTime) {
+ typeMapping.put("date", "OpenAPIDateWithoutTime");
+ } else {
+ typeMapping.put("date", "Date");
+ }
+
+ if (additionalProperties.containsKey(USE_CLASSES)) {
+ setUseClasses(convertPropertyToBooleanAndWriteBack(USE_CLASSES));
+ }
+ additionalProperties.put(USE_CLASSES, useClasses);
+
+ if (additionalProperties.containsKey(VALIDATABLE)) {
+ setValidatable(convertPropertyToBooleanAndWriteBack(VALIDATABLE));
+ }
+ additionalProperties.put(VALIDATABLE, validatable);
+
+ if (additionalProperties.containsKey(API_STATIC_METHOD)) {
+ setApiStaticMethod(convertPropertyToBooleanAndWriteBack(API_STATIC_METHOD));
+ }
+ additionalProperties.put(API_STATIC_METHOD, apiStaticMethod);
+
+ if (additionalProperties.containsKey(COMBINE_DEFERRED)) {
+ setCombineDeferred(convertPropertyToBooleanAndWriteBack(COMBINE_DEFERRED));
+ }
+ additionalProperties.put(COMBINE_DEFERRED, combineDeferred);
+
+ setLenientTypeCast(convertPropertyToBooleanAndWriteBack(LENIENT_TYPE_CAST));
+
+ // make api and model doc path available in mustache template
+ additionalProperties.put("apiDocPath", apiDocPath);
+ additionalProperties.put("modelDocPath", modelDocPath);
+
+ if (!getLibrary().equals(LIBRARY_VAPOR)) {
+ supportingFiles.add(new SupportingFile("Podspec.mustache",
+ "",
+ projectName + ".podspec"));
+ supportingFiles.add(new SupportingFile("Cartfile.mustache",
+ "",
+ "Cartfile"));
+ supportingFiles.add(new SupportingFile("CodableHelper.mustache",
+ sourceFolder,
+ "CodableHelper.swift"));
+ supportingFiles.add(new SupportingFile("JSONDataEncoding.mustache",
+ sourceFolder,
+ "JSONDataEncoding.swift"));
+ supportingFiles.add(new SupportingFile("JSONEncodingHelper.mustache",
+ sourceFolder,
+ "JSONEncodingHelper.swift"));
+ supportingFiles.add(new SupportingFile("git_push.sh.mustache",
+ "",
+ "git_push.sh"));
+ supportingFiles.add(new SupportingFile("SynchronizedDictionary.mustache",
+ sourceFolder,
+ "SynchronizedDictionary.swift"));
+ supportingFiles.add(new SupportingFile("XcodeGen.mustache",
+ "",
+ "project.yml"));
+ supportingFiles.add(new SupportingFile("APIHelper.mustache",
+ sourceFolder,
+ "APIHelper.swift"));
+ supportingFiles.add(new SupportingFile("Models.mustache",
+ sourceFolder,
+ "Models.swift"));
+ }
+ supportingFiles.add(new SupportingFile("Package.swift.mustache",
+ "",
+ "Package.swift"));
+ supportingFiles.add(new SupportingFile("Extensions.mustache",
+ sourceFolder,
+ "Extensions.swift"));
+ supportingFiles.add(new SupportingFile("OpenISO8601DateFormatter.mustache",
+ sourceFolder,
+ "OpenISO8601DateFormatter.swift"));
+ if (useCustomDateWithoutTime) {
+ supportingFiles.add(new SupportingFile("OpenAPIDateWithoutTime.mustache",
+ sourceFolder,
+ "OpenAPIDateWithoutTime.swift"));
+ }
+ supportingFiles.add(new SupportingFile("APIs.mustache",
+ sourceFolder,
+ "APIs.swift"));
+ if (validatable) {
+ supportingFiles.add(new SupportingFile("Validation.mustache",
+ sourceFolder,
+ "Validation.swift"));
+ }
+ supportingFiles.add(new SupportingFile("gitignore.mustache",
+ "",
+ ".gitignore"));
+ supportingFiles.add(new SupportingFile("README.mustache",
+ "",
+ "README.md"));
+ supportingFiles.add(new SupportingFile("swiftformat.mustache",
+ "",
+ ".swiftformat"));
+
+ switch (getLibrary()) {
+ case LIBRARY_ALAMOFIRE:
+ additionalProperties.put("useAlamofire", true);
+ supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache",
+ sourceFolder,
+ "AlamofireImplementations.swift"));
+ break;
+ case LIBRARY_URLSESSION:
+ additionalProperties.put("useURLSession", true);
+ supportingFiles.add(new SupportingFile("URLSessionImplementations.mustache",
+ sourceFolder,
+ "URLSessionImplementations.swift"));
+ break;
+ case LIBRARY_VAPOR:
+ additionalProperties.put("useVapor", true);
+ break;
+ default:
+ break;
+ }
+
+ }
+
+ @Override
+ protected boolean isReservedWord(String word) {
+ return word != null && reservedWords.contains(word); // don't lowercase as super does
+ }
+
+ @Override
+ public String escapeReservedWord(String name) {
+ if (this.reservedWordsMappings().containsKey(name)) {
+ return this.reservedWordsMappings().get(name);
+ }
+ return useBacktickEscapes && !objcCompatible ? "`" + name + "`" : "_" + name;
+ }
+
+ @Override
+ public String modelFileFolder() {
+ return outputFolder + File.separator + sourceFolder
+ + modelPackage().replace('.', File.separatorChar);
+ }
+
+ @Override
+ public String apiFileFolder() {
+ return outputFolder + File.separator + sourceFolder
+ + apiPackage().replace('.', File.separatorChar);
+ }
+
+ @Override
+ public String getTypeDeclaration(Schema p) {
+ if (ModelUtils.isArraySchema(p)) {
+ Schema inner = ModelUtils.getSchemaItems(p);
+ return ModelUtils.isSet(p) ? "Set<" + getTypeDeclaration(inner) + ">"
+ : "[" + getTypeDeclaration(inner) + "]";
+ } else if (ModelUtils.isMapSchema(p)) {
+ Schema inner = ModelUtils.getAdditionalProperties(p);
+ return "[String: " + getTypeDeclaration(inner) + "]";
+ }
+ return super.getTypeDeclaration(p);
+ }
+
+ @Override
+ public String getSchemaType(Schema p) {
+ String openAPIType = super.getSchemaType(p);
+ String type;
+ if (typeMapping.containsKey(openAPIType)) {
+ type = typeMapping.get(openAPIType);
+ if (languageSpecificPrimitives.contains(type) || defaultIncludes.contains(type)) {
+ return type;
+ }
+ } else {
+ type = openAPIType;
+ }
+ return toModelName(type);
+ }
+
+ @Override
+ public boolean isDataTypeFile(String dataType) {
+ return "URL".equals(dataType);
+ }
+
+ @Override
+ public boolean isDataTypeBinary(final String dataType) {
+ return "Data".equals(dataType);
+ }
+
+ /**
+ * Output the proper model name (capitalized).
+ *
+ * @param name the name of the model
+ * @return capitalized model name
+ */
+ @Override
+ public String toModelName(String name) {
+
+ if (modelNameMapping.containsKey(name)) {
+ return modelNameMapping.get(name);
+ }
+
+ // FIXME parameter should not be assigned. Also declare it as "final"
+ name = sanitizeName(name);
+
+ if (!StringUtils.isEmpty(modelNameSuffix) && !isLanguageSpecificType(name)) { // set model suffix
+ name = name + "_" + modelNameSuffix;
+ }
+
+ if (!StringUtils.isEmpty(modelNamePrefix) && !isLanguageSpecificType(name)) { // set model prefix
+ name = modelNamePrefix + "_" + name;
+ }
+
+ // camelize the model name
+ // phone_number => PhoneNumber
+ name = camelize(name);
+
+ // model name cannot use reserved keyword, e.g. return
+ if (isReservedWord(name)) {
+ String modelName = "Model" + name;
+ LOGGER.warn("{} (reserved word) cannot be used as model name. Renamed to {}", name, modelName);
+ return modelName;
+ }
+
+ // model name starts with number
+ if (name.matches("^\\d.*")) {
+ // e.g. 200Response => Model200Response (after camelize)
+ String modelName = "Model" + name;
+ LOGGER.warn("{} (model name starts with number) cannot be used as model name. Renamed to {}", name,
+ modelName);
+ return modelName;
+ }
+
+ return name;
+ }
+
+ /**
+ * Return the capitalized file name of the model.
+ *
+ * @param name the model name
+ * @return the file name of the model
+ */
+ @Override
+ public String toModelFilename(String name) {
+ // should be the same as the model name
+ return toModelName(name);
+ }
+
+ @Override
+ public String toDefaultValue(Schema p) {
+ if (p.getEnum() != null && !p.getEnum().isEmpty()) {
+ if (p.getDefault() != null) {
+ return "." + toEnumVarName(escapeText(String.valueOf(p.getDefault())), p.getType());
+ }
+ }
+ if (p.getDefault() != null) {
+ if (ModelUtils.isIntegerSchema(p) || ModelUtils.isNumberSchema(p) || ModelUtils.isBooleanSchema(p)) {
+ return p.getDefault().toString();
+ } else if (ModelUtils.isDateTimeSchema(p)) {
+ // Datetime time stamps in Swift are expressed as Seconds with Microsecond
+ // precision.
+ // In Java, we need to be creative to get the Timestamp in Microseconds as a
+ // long.
+ Instant instant = ((OffsetDateTime) p.getDefault()).toInstant();
+ long epochMicro = TimeUnit.SECONDS.toMicros(instant.getEpochSecond())
+ + (instant.get(ChronoField.MICRO_OF_SECOND));
+ return "Date(timeIntervalSince1970: " + epochMicro + ".0 / 1_000_000)";
+ } else if (ModelUtils.isStringSchema(p)) {
+ return "\"" + escapeText(String.valueOf(p.getDefault())) + "\"";
+ }
+ // TODO: Handle more cases from `ModelUtils`, such as Date
+ }
+ return null;
+ }
+
+ @Override
+ public String toInstantiationType(Schema p) {
+ if (ModelUtils.isMapSchema(p)) {
+ return getSchemaType(ModelUtils.getAdditionalProperties(p));
+ } else if (ModelUtils.isArraySchema(p)) {
+ String inner = getSchemaType(ModelUtils.getSchemaItems(p));
+ return ModelUtils.isSet(p) ? "Set<" + inner + ">" : "[" + inner + "]";
+ }
+ return null;
+ }
+
+ @Override
+ public String toApiName(String name) {
+ if (name.length() == 0) {
+ return "DefaultAPI";
+ }
+ return camelize(apiNamePrefix + "_" + name) + "API";
+ }
+
+ @Override
+ public String apiDocFileFolder() {
+ return (outputFolder + "/" + apiDocPath).replace("/", File.separator);
+ }
+
+ @Override
+ public String modelDocFileFolder() {
+ return (outputFolder + "/" + modelDocPath).replace("/", File.separator);
+ }
+
+ @Override
+ public String toModelDocFilename(String name) {
+ return toModelName(name);
+ }
+
+ @Override
+ public String toApiDocFilename(String name) {
+ return toApiName(name);
+ }
+
+ @Override
+ public String toOperationId(String operationId) {
+ operationId = camelize(sanitizeName(operationId), LOWERCASE_FIRST_LETTER);
+
+ // Throw exception if method name is empty.
+ // This should not happen but keep the check just in case
+ if (StringUtils.isEmpty(operationId)) {
+ throw new RuntimeException("Empty method name (operationId) not allowed");
+ }
+
+ // method name cannot use reserved keyword, e.g. return
+ if (isReservedWord(operationId)) {
+ String newOperationId = camelize(("call_" + operationId), LOWERCASE_FIRST_LETTER);
+ LOGGER.warn("{} (reserved word) cannot be used as method name. Renamed to {}", operationId, newOperationId);
+ return newOperationId;
+ }
+
+ // operationId starts with a number
+ if (operationId.matches("^\\d.*")) {
+ LOGGER.warn("{} (starting with a number) cannot be used as method name. Renamed to {}", operationId,
+ camelize(sanitizeName("call_" + operationId), LOWERCASE_FIRST_LETTER));
+ operationId = camelize(sanitizeName("call_" + operationId), LOWERCASE_FIRST_LETTER);
+ }
+
+ return operationId;
+ }
+
+ @Override
+ public String toVarName(String name) {
+ // obtain the name from nameMapping directly if provided
+ if (nameMapping.containsKey(name)) {
+ return nameMapping.get(name);
+ }
+
+ // sanitize name
+ name = sanitizeName(name);
+
+ // if it's all upper case, do nothing
+ if (name.matches("^[A-Z_]*$")) {
+ return name;
+ }
+
+ // camelize the variable name
+ // pet_id => petId
+ name = camelize(name, LOWERCASE_FIRST_LETTER);
+
+ // for reserved words surround with `` or append _
+ if (isReservedWord(name)) {
+ name = escapeReservedWord(name);
+ }
+
+ // for words starting with number, append _
+ if (name.matches("^\\d.*")) {
+ name = "_" + name;
+ }
+
+ return name;
+ }
+
+ @Override
+ public String toParamName(String name) {
+ // obtain the name from parameterNameMapping directly if provided
+ if (parameterNameMapping.containsKey(name)) {
+ return parameterNameMapping.get(name);
+ }
+
+ // sanitize name
+ name = sanitizeName(name);
+
+ // replace - with _ e.g. created-at => created_at
+ name = name.replaceAll("-", "_");
+
+ // if it's all upper case, do nothing
+ if (name.matches("^[A-Z_]*$")) {
+ return name;
+ }
+
+ // camelize(lower) the variable name
+ // pet_id => petId
+ name = camelize(name, LOWERCASE_FIRST_LETTER);
+
+ // for reserved words surround with ``
+ if (isReservedWord(name)) {
+ name = escapeReservedWord(name);
+ }
+
+ // for words starting with number, append _
+ if (name.matches("^\\d.*")) {
+ name = "_" + name;
+ }
+
+ return name;
+ }
+
+ @Override
+ public CodegenModel fromModel(String name, Schema model) {
+ Map allDefinitions = ModelUtils.getSchemas(this.openAPI);
+ CodegenModel codegenModel = super.fromModel(name, model);
+ if (codegenModel.description != null) {
+ codegenModel.imports.add("ApiModel");
+ }
+ if (allDefinitions != null) {
+ String parentSchema = codegenModel.parentSchema;
+
+ // multilevel inheritance: reconcile properties of all the parents
+ while (parentSchema != null) {
+ final Schema parentModel = allDefinitions.get(parentSchema);
+ final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent,
+ parentModel);
+ codegenModel = Swift6ClientCodegen.reconcileProperties(codegenModel, parentCodegenModel);
+
+ // get the next parent
+ parentSchema = parentCodegenModel.parentSchema;
+ }
+ }
+ if (hashableModels) {
+ codegenModel.vendorExtensions.put("x-swift-hashable", true);
+ }
+ return codegenModel;
+ }
+
+ @Override
+ public String toEnumValue(String value, String datatype) {
+ // for string, array of string
+ if ("String".equals(datatype) || "[String]".equals(datatype) || "[String: String]".equals(datatype)) {
+ return "\"" + value + "\"";
+ } else {
+ return String.valueOf(value);
+ }
+ }
+
+ @Override
+ public String toEnumDefaultValue(String value, String datatype) {
+ return datatype + "_" + value;
+ }
+
+ @Override
+ public String toEnumVarName(String name, String datatype) {
+ if (enumNameMapping.containsKey(name)) {
+ return enumNameMapping.get(name);
+ }
+
+ if (name.length() == 0) {
+ return "empty";
+ }
+
+ if (enumUnknownDefaultCase) {
+ if (name.equals(enumUnknownDefaultCaseName)) {
+ return camelize(name, LOWERCASE_FIRST_LETTER);
+ }
+ }
+
+ // Reserved Name
+ String nameLowercase = StringUtils.lowerCase(name);
+ if (isReservedWord(nameLowercase)) {
+ return escapeReservedWord(nameLowercase);
+ }
+
+ // Prefix with underscore if name starts with number
+ if (name.matches("\\d.*")) {
+ return "_" + replaceSpecialCharacters(camelize(name, LOWERCASE_FIRST_LETTER));
+ }
+
+ // for symbol, e.g. $, #
+ if (getSymbolName(name) != null) {
+ return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase(Locale.ROOT)),
+ LOWERCASE_FIRST_LETTER);
+ }
+
+ // Camelize only when we have a structure defined below
+ boolean camelized = false;
+ if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) {
+ name = camelize(name, LOWERCASE_FIRST_LETTER);
+ camelized = true;
+ }
+
+ // Check for numerical conversions
+ if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype)
+ || "Float".equals(datatype) || "Double".equals(datatype)) {
+ String varName = "number" + camelize(name);
+ return replaceSpecialCharacters(varName);
+ }
+
+ // If we have already camelized the word, don't progress
+ // any further
+ if (camelized) {
+ return replaceSpecialCharacters(name);
+ }
+
+ char[] separators = { '-', '_', ' ', ':', '(', ')' };
+ return camelize(replaceSpecialCharacters(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators)
+ .replaceAll("[-_ :\\(\\)]", "")),
+ LOWERCASE_FIRST_LETTER);
+ }
+
+ private Boolean isLanguageSpecificType(String name) {
+ return languageSpecificPrimitives.contains(name);
+ }
+
+ private String replaceSpecialCharacters(String name) {
+ for (Map.Entry specialCharacters : specialCharReplacements.entrySet()) {
+ String specialChar = specialCharacters.getKey();
+ String replacement = specialCharacters.getValue();
+ // Underscore is the only special character we'll allow
+ if (!specialChar.equals("_") && name.contains(specialChar)) {
+ name = replaceCharacters(name, specialChar, replacement);
+ }
+ }
+
+ // Fallback, replace unknowns with underscore.
+ name = name.replaceAll("\\W+", "_");
+
+ return name;
+ }
+
+ private String replaceCharacters(String word, String oldValue, String newValue) {
+ if (!word.contains(oldValue)) {
+ return word;
+ }
+ if (word.equals(oldValue)) {
+ return newValue;
+ }
+ int i = word.indexOf(oldValue);
+ String start = word.substring(0, i);
+ String end = recurseOnEndOfWord(word, oldValue, newValue, i);
+ return start + newValue + end;
+ }
+
+ private String recurseOnEndOfWord(String word, String oldValue, String newValue, int lastReplacedValue) {
+ String end = word.substring(lastReplacedValue + 1);
+ if (!end.isEmpty()) {
+ end = titleCase(end);
+ end = replaceCharacters(end, oldValue, newValue);
+ }
+ return end;
+ }
+
+ private String titleCase(final String input) {
+ return input.substring(0, 1).toUpperCase(Locale.ROOT) + input.substring(1);
+ }
+
+ @Override
+ public String toEnumName(CodegenProperty property) {
+ if (enumNameMapping.containsKey(property.name)) {
+ return enumNameMapping.get(property.name);
+ }
+
+ String enumName = toModelName(property.name);
+
+ // Ensure that the enum type doesn't match a reserved word or
+ // the variable name doesn't match the generated enum type or the
+ // Swift compiler will generate an error
+ if (isReservedWord(property.datatypeWithEnum)
+ || toVarName(property.name).equals(property.datatypeWithEnum)) {
+ enumName = property.datatypeWithEnum + "Enum";
+ }
+
+ // TODO: toModelName already does something for names starting with number,
+ // so this code is probably never called
+ if (enumName.matches("\\d.*")) { // starts with number
+ return "_" + enumName;
+ } else {
+ return enumName;
+ }
+ }
+
+ @Override
+ public ModelsMap postProcessModels(ModelsMap objs) {
+ ModelsMap postProcessedModelsEnum = postProcessModelsEnum(objs);
+
+ // We iterate through the list of models, and also iterate through each of the
+ // properties for each model. For each property, if:
+ //
+ // CodegenProperty.name != CodegenProperty.baseName
+ //
+ // then we set
+ //
+ // CodegenProperty.vendorExtensions["x-codegen-escaped-property-name"] = true
+ //
+ // Also, if any property in the model has x-codegen-escaped-property-name=true,
+ // then we mark:
+ //
+ // CodegenModel.vendorExtensions["x-codegen-has-escaped-property-names"] = true
+ //
+ for (ModelMap mo : postProcessedModelsEnum.getModels()) {
+ CodegenModel cm = mo.getModel();
+ boolean modelHasPropertyWithEscapedName = false;
+ for (CodegenProperty prop : cm.allVars) {
+ if (!prop.name.equals(prop.baseName)) {
+ prop.vendorExtensions.put("x-codegen-escaped-property-name", true);
+ modelHasPropertyWithEscapedName = true;
+ }
+
+ if (prop.vendorExtensions.containsKey("x-null-encodable")) {
+ if (prop.vendorExtensions.get("x-null-encodable").toString().equals("true")) {
+ if (prop.defaultValue == null || prop.defaultValue.equals("null")) {
+ prop.vendorExtensions.put("x-null-encodable-default-value", ".encodeNull");
+ } else {
+ prop.vendorExtensions.put("x-null-encodable-default-value",
+ ".encodeValue(" + prop.defaultValue + ")");
+ }
+ }
+ }
+ }
+ if (modelHasPropertyWithEscapedName) {
+ cm.vendorExtensions.put("x-codegen-has-escaped-property-names", true);
+ }
+ }
+
+ return postProcessedModelsEnum;
+ }
+
+ @Override
+ public void postProcessModelProperty(CodegenModel model, CodegenProperty property) {
+ super.postProcessModelProperty(model, property);
+
+ boolean isSwiftScalarType = property.isInteger || property.isLong || property.isFloat
+ || property.isDouble || property.isBoolean;
+ if ((!property.required || property.isNullable) && isSwiftScalarType) {
+ // Optional scalar types like Int?, Int64?, Float?, Double?, and Bool?
+ // do not translate to Objective-C. So we want to flag those
+ // properties in case we want to put special code in the templates
+ // which provide Objective-C compatibility.
+ property.vendorExtensions.put("x-swift-optional-scalar", true);
+ }
+ }
+
+ @Override
+ public String escapeQuotationMark(String input) {
+ // remove " to avoid code injection
+ return input.replace("\"", "");
+ }
+
+ @Override
+ public String escapeUnsafeCharacters(String input) {
+ return input.replace("*/", "*_/").replace("/*", "/_*");
+ }
+
+ @Override
+ public void postProcessFile(File file, String fileType) {
+ if (file == null) {
+ return;
+ }
+ String swiftPostProcessFile = System.getenv("SWIFT_POST_PROCESS_FILE");
+ if (StringUtils.isEmpty(swiftPostProcessFile)) {
+ return; // skip if SWIFT_POST_PROCESS_FILE env variable is not defined
+ }
+ // only process files with swift extension
+ if ("swift".equals(FilenameUtils.getExtension(file.toString()))) {
+ String command = swiftPostProcessFile + " " + file;
+ try {
+ Process p = Runtime.getRuntime().exec(command);
+ int exitValue = p.waitFor();
+ if (exitValue != 0) {
+ LOGGER.error("Error running the command ({}). Exit value: {}", command, exitValue);
+ } else {
+ LOGGER.info("Successfully executed: {}", command);
+ }
+ } catch (InterruptedException | IOException e) {
+ LOGGER.error("Error running the command ({}). Exception: {}", command, e.getMessage());
+ // Restore interrupted state
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ @Override
+ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) {
+ OperationMap objectMap = objs.getOperations();
+
+ HashMap modelMaps = ModelMap.toCodegenModelMap(allModels);
+
+ List operations = objectMap.getOperation();
+ for (CodegenOperation operation : operations) {
+ for (CodegenParameter cp : operation.allParams) {
+ cp.vendorExtensions.put("x-swift-example", constructExampleCode(cp, modelMaps, new HashSet<>()));
+ }
+ }
+ return objs;
+ }
+
+ public String constructExampleCode(CodegenParameter codegenParameter, HashMap modelMaps,
+ Set visitedModels) {
+ if (codegenParameter.isArray) { // array
+ return "[" + constructExampleCode(codegenParameter.items, modelMaps, visitedModels) + "]";
+ } else if (codegenParameter.isMap) { // TODO: map, file type
+ return "\"TODO\"";
+ } else if (languageSpecificPrimitives.contains(codegenParameter.dataType)) { // primitive type
+ if ("String".equals(codegenParameter.dataType) || "Character".equals(codegenParameter.dataType)) {
+ if (StringUtils.isEmpty(codegenParameter.example)) {
+ return "\"" + codegenParameter.example + "\"";
+ } else {
+ return "\"" + codegenParameter.paramName + "_example\"";
+ }
+ } else if ("Bool".equals(codegenParameter.dataType)) { // boolean
+ if (Boolean.parseBoolean(codegenParameter.example)) {
+ return "true";
+ } else {
+ return "false";
+ }
+ } else if ("URL".equals(codegenParameter.dataType)) { // URL
+ return "URL(string: \"https://example.com\")!";
+ } else if ("Data".equals(codegenParameter.dataType)) { // URL
+ return "Data([9, 8, 7])";
+ } else if ("Date".equals(codegenParameter.dataType)) { // date
+ return "Date()";
+ } else { // numeric
+ if (StringUtils.isEmpty(codegenParameter.example)) {
+ return codegenParameter.example;
+ } else {
+ return "987";
+ }
+ }
+ } else { // model
+ // look up the model
+ if (modelMaps.containsKey(codegenParameter.dataType)) {
+ if (visitedModels.contains(codegenParameter.dataType)) {
+ // recursive/self-referencing model, simply return nil to avoid stackoverflow
+ return "nil";
+ } else {
+ visitedModels.add(codegenParameter.dataType);
+ return constructExampleCode(modelMaps.get(codegenParameter.dataType), modelMaps, visitedModels);
+ }
+ } else {
+ // LOGGER.error("Error in constructing examples. Failed to look up the model " +
+ // codegenParameter.dataType);
+ return "TODO";
+ }
+ }
+ }
+
+ public String constructExampleCode(CodegenProperty codegenProperty, HashMap modelMaps,
+ Set visitedModels) {
+ if (codegenProperty.isArray) { // array
+ return "[" + constructExampleCode(codegenProperty.items, modelMaps, visitedModels) + "]";
+ } else if (codegenProperty.isMap) { // TODO: map, file type
+ return "\"TODO\"";
+ } else if (languageSpecificPrimitives.contains(codegenProperty.dataType)) { // primitive type
+ if ("String".equals(codegenProperty.dataType) || "Character".equals(codegenProperty.dataType)) {
+ if (StringUtils.isEmpty(codegenProperty.example)) {
+ return "\"" + codegenProperty.example + "\"";
+ } else {
+ return "\"" + codegenProperty.name + "_example\"";
+ }
+ } else if ("Bool".equals(codegenProperty.dataType)) { // boolean
+ if (Boolean.parseBoolean(codegenProperty.example)) {
+ return "true";
+ } else {
+ return "false";
+ }
+ } else if ("URL".equals(codegenProperty.dataType)) { // URL
+ return "URL(string: \"https://example.com\")!";
+ } else if ("Date".equals(codegenProperty.dataType)) { // date
+ return "Date()";
+ } else { // numeric
+ if (StringUtils.isEmpty(codegenProperty.example)) {
+ return codegenProperty.example;
+ } else {
+ return "123";
+ }
+ }
+ } else {
+ // look up the model
+ if (modelMaps.containsKey(codegenProperty.dataType)) {
+ if (visitedModels.contains(codegenProperty.dataType)) {
+ // recursive/self-referencing model, simply return nil to avoid stackoverflow
+ return "nil";
+ } else {
+ visitedModels.add(codegenProperty.dataType);
+ return constructExampleCode(modelMaps.get(codegenProperty.dataType), modelMaps, visitedModels);
+ }
+ } else {
+ // LOGGER.error("Error in constructing examples. Failed to look up the model " +
+ // codegenProperty.dataType);
+ return "\"TODO\"";
+ }
+ }
+ }
+
+ public String constructExampleCode(CodegenModel codegenModel, HashMap modelMaps,
+ Set visitedModels) {
+ String example;
+ example = codegenModel.name + "(";
+ List propertyExamples = new ArrayList<>();
+ for (CodegenProperty codegenProperty : codegenModel.vars) {
+ propertyExamples
+ .add(codegenProperty.name + ": " + constructExampleCode(codegenProperty, modelMaps, visitedModels));
+ }
+ example += StringUtils.join(propertyExamples, ", ");
+ example += ")";
+ return example;
+ }
+
+ @Override
+ public void postProcess() {
+ System.out.println("################################################################################");
+ System.out.println("# Thanks for using OpenAPI Generator. #");
+ System.out
+ .println("# Please consider donation to help us maintain this project \uD83D\uDE4F #");
+ System.out.println("# https://opencollective.com/openapi_generator/donate #");
+ System.out.println("# #");
+ System.out.println("# swift6 generator is contributed by Bruno Coelho (https://github.com/4brunu). #");
+ System.out
+ .println("# Please support his work directly via https://paypal.com/paypalme/4brunu \uD83D\uDE4F #");
+ System.out.println("################################################################################");
+ }
+
+ @Override
+ public GeneratorLanguage generatorLanguage() {
+ return GeneratorLanguage.SWIFT;
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig
index 00a51f289abe..c7893861026f 100644
--- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig
+++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig
@@ -115,6 +115,7 @@ org.openapitools.codegen.languages.RClientCodegen
org.openapitools.codegen.languages.RubyClientCodegen
org.openapitools.codegen.languages.RubyOnRailsServerCodegen
org.openapitools.codegen.languages.RubySinatraServerCodegen
+org.openapitools.codegen.languages.RustAxumServerCodegen
org.openapitools.codegen.languages.RustClientCodegen
org.openapitools.codegen.languages.RustServerCodegen
org.openapitools.codegen.languages.ScalatraServerCodegen
@@ -135,6 +136,7 @@ org.openapitools.codegen.languages.StaticDocCodegen
org.openapitools.codegen.languages.StaticHtmlGenerator
org.openapitools.codegen.languages.StaticHtml2Generator
org.openapitools.codegen.languages.Swift5ClientCodegen
+org.openapitools.codegen.languages.Swift6ClientCodegen
org.openapitools.codegen.languages.SwiftCombineClientCodegen
org.openapitools.codegen.languages.TypeScriptClientCodegen
org.openapitools.codegen.languages.TypeScriptAngularClientCodegen
@@ -150,4 +152,3 @@ org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen
org.openapitools.codegen.languages.WsdlSchemaCodegen
org.openapitools.codegen.languages.XojoClientCodegen
org.openapitools.codegen.languages.ZapierClientCodegen
-org.openapitools.codegen.languages.RustAxumServerCodegen
diff --git a/modules/openapi-generator/src/main/resources/swift6/APIHelper.mustache b/modules/openapi-generator/src/main/resources/swift6/APIHelper.mustache
new file mode 100644
index 000000000000..d4583787564b
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/APIHelper.mustache
@@ -0,0 +1,122 @@
+// APIHelper.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation{{#useVapor}}
+import Vapor{{/useVapor}}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct APIHelper {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func rejectNil(_ source: [String: Any?]) -> [String: Any]? {
+ let destination = source.reduce(into: [String: Any]()) { result, item in
+ if let value = item.value {
+ result[item.key] = value
+ }
+ }
+
+ if destination.isEmpty {
+ return nil
+ }
+ return destination
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] {
+ return source.reduce(into: [String: String]()) { result, item in
+ if let collection = item.value as? [Any?] {
+ result[item.key] = collection
+ .compactMap { value in convertAnyToString(value) }
+ .joined(separator: ",")
+ } else if let value: Any = item.value {
+ result[item.key] = convertAnyToString(value)
+ }
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? {
+ guard let source = source else {
+ return nil
+ }
+
+ return source.reduce(into: [String: Any]()) { result, item in
+ switch item.value {
+ case let x as Bool:
+ result[item.key] = x.description
+ default:
+ result[item.key] = item.value
+ }
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func convertAnyToString(_ value: Any?) -> String? {
+ guard let value = value else { return nil }
+ if let value = value as? any RawRepresentable {
+ return "\(value.rawValue)"
+ } else {
+ return "\(value)"
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValueToPathItem(_ source: Any) -> Any {
+ if let collection = source as? [Any?] {
+ return collection
+ .compactMap { value in convertAnyToString(value) }
+ .joined(separator: ",")
+ } else if let value = source as? any RawRepresentable {
+ return "\(value.rawValue)"
+ }
+ return source
+ }
+
+ /// maps all values from source to query parameters
+ ///
+ /// explode attribute is respected: collection values might be either joined or split up into separate key value pairs
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? {
+ let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in
+ if let collection = item.value.wrappedValue as? [Any?] {
+
+ let collectionValues: [String] = collection.compactMap { value in convertAnyToString(value) }
+
+ if !item.value.isExplode {
+ result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ",")))
+ } else {
+ collectionValues
+ .forEach { value in
+ result.append(URLQueryItem(name: item.key, value: value))
+ }
+ }
+
+ } else if let value = item.value.wrappedValue {
+ result.append(URLQueryItem(name: item.key, value: convertAnyToString(value)))
+ }
+ }
+
+ if destination.isEmpty {
+ return nil
+ }
+ return destination.sorted { $0.name < $1.name }
+ }
+
+ /// maps all values from source to query parameters
+ ///
+ /// collection values are always exploded
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? {
+ let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in
+ if let collection = item.value as? [Any?] {
+ collection
+ .compactMap { value in convertAnyToString(value) }
+ .forEach { value in
+ result.append(URLQueryItem(name: item.key, value: value))
+ }
+
+ } else if let value = item.value {
+ result.append(URLQueryItem(name: item.key, value: convertAnyToString(value)))
+ }
+ }
+
+ if destination.isEmpty {
+ return nil
+ }
+ return destination.sorted { $0.name < $1.name }
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/APIs.mustache b/modules/openapi-generator/src/main/resources/swift6/APIs.mustache
new file mode 100644
index 000000000000..4c2de503f4e5
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/APIs.mustache
@@ -0,0 +1,128 @@
+// APIs.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif{{#useVapor}}
+import Vapor{{/useVapor}}{{#useAlamofire}}
+import Alamofire{{/useAlamofire}}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{projectName}}API: @unchecked Sendable {
+ private init() {}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static let shared = {{projectName}}API()
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var basePath = "{{{basePath}}}"{{#useVapor}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var customHeaders: HTTPHeaders = [:]
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var apiClient: Vapor.Client? = nil
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var apiWrapper: (inout Vapor.ClientRequest) throws -> () = { _ in }
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var contentConfiguration = ContentConfiguration.default(){{/useVapor}}{{^useVapor}}{{/useVapor}}{{^useVapor}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var customHeaders: [String: String] = [:]
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var credential: URLCredential?{{#useAlamofire}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory(){{/useAlamofire}}{{#useURLSession}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory(){{/useURLSession}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var apiResponseQueue: DispatchQueue = .main
+ /// Configures the range of HTTP status codes that will result in a successful response
+ ///
+ /// If a HTTP status code is outside of this range the response will be interpreted as failed.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var successfulStatusCodeRange: Range = 200..<300{{/useVapor}}{{#useAlamofire}}
+ /// ResponseSerializer that will be used by the generator for `Data` responses
+ ///
+ /// If unchanged, Alamofires default `DataResponseSerializer` will be used.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var dataResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(DataResponseSerializer())
+ /// ResponseSerializer that will be used by the generator for `String` responses
+ ///
+ /// If unchanged, Alamofires default `StringResponseSerializer` will be used.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var stringResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(StringResponseSerializer()){{/useAlamofire}}
+}{{^useVapor}}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class RequestBuilder: @unchecked Sendable {
+ var credential: URLCredential?
+ var headers: [String: String]
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let parameters: [String: Any]?
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let method: String
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let URLString: String
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let requestTask: RequestTask = RequestTask()
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let requiresAuthentication: Bool
+
+ /// Optional block to obtain a reference to the request's progress instance when available.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var onProgressReady: ((Progress) -> Void)?
+
+ required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
+ self.method = method
+ self.URLString = URLString
+ self.parameters = parameters
+ self.headers = headers
+ self.requiresAuthentication = requiresAuthentication
+
+ addHeaders({{projectName}}API.shared.customHeaders)
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addHeaders(_ aHeaders: [String: String]) {
+ for (header, value) in aHeaders {
+ headers[header] = value
+ }
+ }
+
+ @discardableResult
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.shared.apiResponseQueue, _ completion: @Sendable @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> RequestTask {
+ return requestTask
+ }
+
+ {{#useAsyncAwait}}
+ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
+ @discardableResult
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute() async throws(ErrorResponse) -> Response {
+ do {
+ let requestTask = self.requestTask
+ return try await withTaskCancellationHandler {
+ try Task.checkCancellation()
+ return try await withCheckedThrowingContinuation { continuation in
+ guard !Task.isCancelled else {
+ continuation.resume(throwing: CancellationError())
+ return
+ }
+
+ self.execute { result in
+ switch result {
+ case let .success(response):
+ nonisolated(unsafe) let response = response
+ continuation.resume(returning: response)
+ case let .failure(error):
+ continuation.resume(throwing: error)
+ }
+ }
+ }
+ } onCancel: {
+ requestTask.cancel()
+ }
+ } catch {
+ if let errorResponse = error as? ErrorResponse {
+ throw errorResponse
+ } else {
+ throw ErrorResponse.error(-3, nil, nil, error)
+ }
+ }
+ }
+
+ {{/useAsyncAwait}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func addHeader(name: String, value: String) -> Self {
+ if !value.isEmpty {
+ headers[name] = value
+ }
+ return self
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func addCredential() -> Self {
+ credential = {{projectName}}API.shared.credential
+ return self
+ }
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol RequestBuilderFactory {
+ func getNonDecodableBuilder() -> RequestBuilder.Type
+ func getBuilder() -> RequestBuilder.Type
+}{{/useVapor}}
diff --git a/modules/openapi-generator/src/main/resources/swift6/Cartfile.mustache b/modules/openapi-generator/src/main/resources/swift6/Cartfile.mustache
new file mode 100644
index 000000000000..db44684151fd
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/Cartfile.mustache
@@ -0,0 +1,4 @@
+github "Flight-School/AnyCodable" ~> 0.6{{#useAlamofire}}
+github "Alamofire/Alamofire" ~> 5.9{{/useAlamofire}}{{#usePromiseKit}}
+github "mxcl/PromiseKit" ~> 8.1{{/usePromiseKit}}{{#useRxSwift}}
+github "ReactiveX/RxSwift" ~> 6.7{{/useRxSwift}}
diff --git a/modules/openapi-generator/src/main/resources/swift6/CodableHelper.mustache b/modules/openapi-generator/src/main/resources/swift6/CodableHelper.mustache
new file mode 100644
index 000000000000..6f9a5e989472
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/CodableHelper.mustache
@@ -0,0 +1,52 @@
+//
+// CodableHelper.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class CodableHelper: @unchecked Sendable {
+ private init() {}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static let shared = CodableHelper()
+
+ private var customDateFormatter: DateFormatter?
+ private var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter()
+
+ private var customJSONDecoder: JSONDecoder?
+ private lazy var defaultJSONDecoder: JSONDecoder = {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .formatted(dateFormatter)
+ return decoder
+ }()
+
+ private var customJSONEncoder: JSONEncoder?
+ private lazy var defaultJSONEncoder: JSONEncoder = {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .formatted(dateFormatter)
+ encoder.outputFormatting = .prettyPrinted
+ return encoder
+ }()
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var dateFormatter: DateFormatter {
+ get { return customDateFormatter ?? defaultDateFormatter }
+ set { customDateFormatter = newValue }
+ }
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var jsonDecoder: JSONDecoder {
+ get { return customJSONDecoder ?? defaultJSONDecoder }
+ set { customJSONDecoder = newValue }
+ }
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var jsonEncoder: JSONEncoder {
+ get { return customJSONEncoder ?? defaultJSONEncoder }
+ set { customJSONEncoder = newValue }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func decode(_ type: T.Type, from data: Data) -> Swift.Result where T: Decodable {
+ return Swift.Result { try jsonDecoder.decode(type, from: data) }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func encode(_ value: T) -> Swift.Result where T: Encodable {
+ return Swift.Result { try jsonEncoder.encode(value) }
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/Extensions.mustache b/modules/openapi-generator/src/main/resources/swift6/Extensions.mustache
new file mode 100644
index 000000000000..f5d96f2077c5
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/Extensions.mustache
@@ -0,0 +1,286 @@
+// Extensions.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+#if canImport(AnyCodable)
+import AnyCodable
+#endif{{#usePromiseKit}}
+@preconcurrency import PromiseKit{{/usePromiseKit}}{{#useVapor}}
+import Vapor{{/useVapor}}{{^useVapor}}
+
+extension Bool: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Float: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Int: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Int32: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Int64: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Double: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Decimal: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension String: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension URL: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension UUID: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension RawRepresentable where RawValue: JSONEncodable {
+ func encodeToJSON() -> Any { return self.rawValue }
+}
+
+private func encodeIfPossible(_ object: T) -> Any {
+ if let encodableObject = object as? JSONEncodable {
+ return encodableObject.encodeToJSON()
+ } else {
+ return object
+ }
+}
+
+extension Array: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return self.map(encodeIfPossible)
+ }
+}
+
+extension Set: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return Array(self).encodeToJSON()
+ }
+}
+
+extension Dictionary: JSONEncodable {
+ func encodeToJSON() -> Any {
+ var dictionary = [AnyHashable: Any]()
+ for (key, value) in self {
+ dictionary[key] = encodeIfPossible(value)
+ }
+ return dictionary
+ }
+}
+
+extension Data: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return self.base64EncodedString(options: Data.Base64EncodingOptions())
+ }
+}
+
+extension Date: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return CodableHelper.shared.dateFormatter.string(from: self)
+ }
+}
+
+extension JSONEncodable where Self: Encodable {
+ func encodeToJSON() -> Any {
+ guard let data = try? CodableHelper.shared.jsonEncoder.encode(self) else {
+ fatalError("Could not encode to json: \(self)")
+ }
+ return data.encodeToJSON()
+ }
+}{{/useVapor}}{{#generateModelAdditionalProperties}}
+
+extension String: @retroactive CodingKey {
+
+ public var stringValue: String {
+ return self
+ }
+
+ public init?(stringValue: String) {
+ self.init(stringLiteral: stringValue)
+ }
+
+ public var intValue: Int? {
+ return nil
+ }
+
+ public init?(intValue: Int) {
+ return nil
+ }
+
+}
+
+extension KeyedEncodingContainerProtocol {
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable {
+ var arrayContainer = nestedUnkeyedContainer(forKey: key)
+ try arrayContainer.encode(contentsOf: values)
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable {
+ if let values = values {
+ try encodeArray(values, forKey: key)
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable {
+ for (key, value) in pairs {
+ try encode(value, forKey: key)
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable {
+ if let pairs = pairs {
+ try encodeMap(pairs)
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encode(_ value: Decimal, forKey key: Self.Key) throws {
+ let decimalNumber = NSDecimalNumber(decimal: value)
+ let numberFormatter = NumberFormatter()
+ numberFormatter.numberStyle = .decimal
+ numberFormatter.locale = Locale(identifier: "en_US")
+ let formattedString = numberFormatter.string(from: decimalNumber) ?? "\(value)"
+ try encode(formattedString, forKey: key)
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws {
+ if let value = value {
+ try encode(value, forKey: key)
+ }
+ }
+}
+
+extension KeyedDecodingContainerProtocol {
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable {
+ var tmpArray = [T]()
+
+ var nestedContainer = try nestedUnkeyedContainer(forKey: key)
+ while !nestedContainer.isAtEnd {
+ let arrayValue = try nestedContainer.decode(T.self)
+ tmpArray.append(arrayValue)
+ }
+
+ return tmpArray
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable {
+ var tmpArray: [T]?
+
+ if contains(key) {
+ tmpArray = try decodeArray(T.self, forKey: key)
+ }
+
+ return tmpArray
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable {
+ var map: [Self.Key: T] = [:]
+
+ for key in allKeys {
+ if !excludedKeys.contains(key) {
+ let value = try decode(T.self, forKey: key)
+ map[key] = value
+ }
+ }
+
+ return map
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal {
+ let stringValue = try decode(String.self, forKey: key)
+ guard let decimalValue = Decimal(string: stringValue) else {
+ let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
+ throw DecodingError.typeMismatch(type, context)
+ }
+
+ return decimalValue
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? {
+ guard let stringValue = try decodeIfPresent(String.self, forKey: key) else {
+ return nil
+ }
+ guard let decimalValue = Decimal(string: stringValue) else {
+ let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
+ throw DecodingError.typeMismatch(type, context)
+ }
+
+ return decimalValue
+ }
+
+}{{/generateModelAdditionalProperties}}{{^useVapor}}
+
+extension HTTPURLResponse {
+ var isStatusCodeSuccessful: Bool {
+ return {{projectName}}API.shared.successfulStatusCodeRange.contains(statusCode)
+ }
+}{{/useVapor}}{{#usePromiseKit}}
+
+extension RequestBuilder {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func execute() -> Promise> {
+ let deferred = Promise>.pending()
+ self.execute { result in
+ switch result {
+ case let .success(response):
+ deferred.resolver.fulfill(response)
+ case let .failure(error):
+ deferred.resolver.reject(error)
+ }
+ }
+ return deferred.promise
+ }
+}{{/usePromiseKit}}{{#useVapor}}
+
+extension UUID: Content { }
+
+extension URL: Content { }
+
+extension Bool: Content { }
+
+extension Set: ResponseEncodable where Element: Content {
+ public func encodeResponse(for request: Vapor.Request) -> EventLoopFuture {
+ let response = Vapor.Response()
+ do {
+ try response.content.encode(Array(self))
+ } catch {
+ return request.eventLoop.makeFailedFuture(error)
+ }
+ return request.eventLoop.makeSucceededFuture(response)
+ }
+}
+
+extension Set: RequestDecodable where Element: Content {
+ public static func decodeRequest(_ request: Vapor.Request) -> EventLoopFuture {
+ do {
+ let content = try request.content.decode([Element].self)
+ return request.eventLoop.makeSucceededFuture(Set(content))
+ } catch {
+ return request.eventLoop.makeFailedFuture(error)
+ }
+ }
+}
+
+extension Set: Content where Element: Content { }
+
+extension AnyCodable: Content {}{{/useVapor}}
diff --git a/modules/openapi-generator/src/main/resources/swift6/JSONDataEncoding.mustache b/modules/openapi-generator/src/main/resources/swift6/JSONDataEncoding.mustache
new file mode 100644
index 000000000000..bfc766127af9
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/JSONDataEncoding.mustache
@@ -0,0 +1,56 @@
+//
+// JSONDataEncoding.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct JSONDataEncoding {
+
+ // MARK: Properties
+
+ private static let jsonDataKey = "jsonData"
+
+ // MARK: Encoding
+
+ /// Creates a URL request by encoding parameters and applying them onto an existing request.
+ ///
+ /// - parameter urlRequest: The request to have parameters applied.
+ /// - parameter parameters: The parameters to apply. This should have a single key/value
+ /// pair with "jsonData" as the key and a Data object as the value.
+ ///
+ /// - throws: An `Error` if the encoding process encounters an error.
+ ///
+ /// - returns: The encoded request.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest {
+ var urlRequest = urlRequest
+
+ guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else {
+ return urlRequest
+ }
+
+ if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
+ urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ }
+
+ urlRequest.httpBody = jsonData
+
+ return urlRequest
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func encodingParameters(jsonData: Data?) -> [String: Any]? {
+ var returnedParams: [String: Any]?
+ if let jsonData = jsonData, !jsonData.isEmpty {
+ var params: [String: Any] = [:]
+ params[jsonDataKey] = jsonData
+ returnedParams = params
+ }
+ return returnedParams
+ }
+
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/JSONEncodingHelper.mustache b/modules/openapi-generator/src/main/resources/swift6/JSONEncodingHelper.mustache
new file mode 100644
index 000000000000..311f6b54bdc0
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/JSONEncodingHelper.mustache
@@ -0,0 +1,45 @@
+//
+// JSONEncodingHelper.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class JSONEncodingHelper {
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? {
+ var params: [String: Any]?
+
+ // Encode the Encodable object
+ if let encodableObj = encodableObj {
+ let encodeResult = CodableHelper.shared.encode(encodableObj)
+ do {
+ let data = try encodeResult.get()
+ params = JSONDataEncoding.encodingParameters(jsonData: data)
+ } catch {
+ print(error.localizedDescription)
+ }
+ }
+
+ return params
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? {
+ var params: [String: Any]?
+
+ if let encodableObj = encodableObj {
+ do {
+ let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted)
+ params = JSONDataEncoding.encodingParameters(jsonData: data)
+ } catch {
+ print(error.localizedDescription)
+ return nil
+ }
+ }
+
+ return params
+ }
+
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/Models.mustache b/modules/openapi-generator/src/main/resources/swift6/Models.mustache
new file mode 100644
index 000000000000..249a44cebb9b
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/Models.mustache
@@ -0,0 +1,176 @@
+// Models.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif{{#useAlamofire}}
+import Alamofire{{/useAlamofire}}
+
+protocol JSONEncodable {
+ func encodeToJSON() -> Any
+}
+
+/// An enum where the last case value can be used as a default catch-all.
+protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable
+where RawValue: Decodable, AllCases: BidirectionalCollection {}
+
+extension CaseIterableDefaultsLast {
+ /// Initializes an enum such that if a known raw value is found, then it is decoded.
+ /// Otherwise the last case is used.
+ /// - Parameter decoder: A decoder.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws {
+ if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) {
+ self = value
+ } else if let lastValue = Self.allCases.last {
+ self = lastValue
+ } else {
+ throw DecodingError.valueNotFound(
+ Self.Type.self,
+ .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast")
+ )
+ }
+ }
+}
+
+/// A flexible type that can be encoded (`.encodeNull` or `.encodeValue`)
+/// or not encoded (`.encodeNothing`). Intended for request payloads.
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum NullEncodable: Hashable {
+ case encodeNothing
+ case encodeNull
+ case encodeValue(Wrapped)
+}
+
+extension NullEncodable: Codable where Wrapped: Codable {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ if let value = try? container.decode(Wrapped.self) {
+ self = .encodeValue(value)
+ } else if container.decodeNil() {
+ self = .encodeNull
+ } else {
+ self = .encodeNothing
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .encodeNothing: return
+ case .encodeNull: try container.encodeNil()
+ case .encodeValue(let wrapped): try container.encode(wrapped)
+ }
+ }
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum ErrorResponse: Error {
+ case error(Int, Data?, URLResponse?, Error)
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum DownloadException: Error {
+ case responseDataMissing
+ case responseFailed
+ case requestMissing
+ case requestMissingPath
+ case requestMissingURL
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum DecodableRequestBuilderError: Error {
+ case emptyDataResponse
+ case nilHTTPResponse
+ case unsuccessfulHTTPStatusCode
+ case jsonDecoding(DecodingError)
+ case generalError(Error)
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class Response {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let statusCode: Int
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let header: [String: String]
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let body: T
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let bodyData: Data?
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(statusCode: Int, header: [String: String], body: T, bodyData: Data?) {
+ self.statusCode = statusCode
+ self.header = header
+ self.body = body
+ self.bodyData = bodyData
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} convenience init(response: HTTPURLResponse, body: T, bodyData: Data?) {
+ let rawHeader = response.allHeaderFields
+ var responseHeader = [String: String]()
+ for (key, value) in rawHeader {
+ if let key = key.base as? String, let value = value as? String {
+ responseHeader[key] = value
+ }
+ }
+ self.init(statusCode: response.statusCode, header: responseHeader, body: body, bodyData: bodyData)
+ }
+}{{#useAlamofire}}
+
+/// Type-erased ResponseSerializer
+///
+/// This is needed in order to use `ResponseSerializer` as a Type in `Configuration`. Obsolete with `any` keyword in Swift >= 5.7
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct AnyResponseSerializer: ResponseSerializer {
+
+ let _serialize: (URLRequest?, HTTPURLResponse?, Data?, Error?) throws -> T
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(_ delegatee: V) where V.SerializedObject == T {
+ _serialize = delegatee.serialize
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
+ try _serialize(request, response, data, error)
+ }
+}{{/useAlamofire}}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} final class RequestTask{{#useAsyncAwait}}: @unchecked Sendable{{/useAsyncAwait}} {
+ private var lock = NSRecursiveLock()
+{{#useAlamofire}}
+ private var request: Request?
+
+ internal func set(request: Request) {
+ lock.withLock {
+ self.request = request
+ }
+ }
+
+ internal func get() -> Request? {
+ lock.withLock {
+ request
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func cancel() {
+ lock.withLock {
+ request?.cancel()
+ request = nil
+ }
+ }
+{{/useAlamofire}}
+{{^useAlamofire}}
+ private var task: URLSessionDataTaskProtocol?
+
+ internal func set(task: URLSessionDataTaskProtocol) {
+ lock.withLock {
+ self.task = task
+ }
+ }
+
+ internal func get() -> URLSessionDataTaskProtocol? {
+ lock.withLock {
+ task
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func cancel() {
+ lock.withLock {
+ task?.cancel()
+ task = nil
+ }
+ }
+{{/useAlamofire}}
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/OpenAPIDateWithoutTime.mustache b/modules/openapi-generator/src/main/resources/swift6/OpenAPIDateWithoutTime.mustache
new file mode 100644
index 000000000000..5a0c0b0d6fb2
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/OpenAPIDateWithoutTime.mustache
@@ -0,0 +1,98 @@
+// OpenAPIDateWithoutTime.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+/// Represents a date without time information (e.g. a birthday) for transmission from and to a REST API
+///
+/// This type is used as a representation for openapi specs `date` format which does not contain
+/// time information as opposed to the `date-time` format. Although it internally uses `Date` for
+/// (de-)serialization as well the generator needs to be able to distinguish between the two formats.
+/// - note: As `Date` is agnostic to timezones (and calendars), timezone information is needed to be able to add
+/// an appropriate padding in order to transform to GMT+0 which is the assumed timezone in ISO 8601.
+/// When decoding, GMT+0 can be assumed (again: ISO8601) so there is no padding necessary and wrappedDate
+/// can be used safely.
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct OpenAPIDateWithoutTime: Codable, Hashable, Equatable {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let wrappedDate: Date
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let timezone: TimeZone
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: CodingKey, CaseIterable {
+ case wrappedDate
+ case timezone
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum DecodingError: Error {
+ case notADateString
+ }
+
+ /// On decoding ISO8601 timezone is assumed
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+
+ let dateString = try container.decode(String.self)
+ guard let date = OpenISO8601DateFormatter.withoutTime.date(from: dateString) else {
+ throw DecodingError.notADateString
+ }
+ self.wrappedDate = date
+
+ self.timezone = OpenISO8601DateFormatter.withoutTime.timeZone
+ }
+
+ /// Convenience Initializer which is useful when dealing with optionals a lot like e.g. in API mappers
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init?(wrappedDate: Date?, timezone: TimeZone = .current) {
+ guard let wrappedDate = wrappedDate else {
+ return nil
+ }
+
+ self.init(wrappedDate: wrappedDate, timezone: timezone)
+ }
+
+ /// Designated Initializer for `OpenAPIDateWithoutTime`
+ ///
+ /// Since usually `Date`s without time components - as e.g. birthdays - are created Calendar- and timezone-aware
+ // it is important to also provide a timezone so that the generator is able to normalize the supplied Date to ISO8601 (GMT+0)
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(wrappedDate: Date, timezone: TimeZone) {
+ self.wrappedDate = wrappedDate
+ self.timezone = timezone
+ }
+
+ /// Only the wrappedDate is encoded normalized to GMT+0 with an offset derived from the supplied Timezone
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ try container.encode(OpenISO8601DateFormatter.withoutTime.string(from: normalizedWrappedDate()))
+ }
+
+ /// Normalizes the wrappedDate to GMT+0 according to the supplied timezone
+ fileprivate func normalizedWrappedDate() -> Date {
+ return wrappedDate.addingTimeInterval(
+ Double(timezone.secondsFromGMT(for: wrappedDate)))
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func == (lhs: Self, rhs: Self) -> Bool {
+ Calendar.current.compare(lhs.wrappedDate, to: rhs.wrappedDate, toGranularity: .day) == .orderedSame
+ }
+}
+
+extension OpenAPIDateWithoutTime: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return OpenISO8601DateFormatter.withoutTime.string(from: self.normalizedWrappedDate())
+ }
+}
+
+extension OpenAPIDateWithoutTime: RawRepresentable {
+ public typealias RawValue = String
+ public init?(rawValue: String) {
+ if let date = OpenISO8601DateFormatter.withoutTime.date(from: rawValue) {
+ self.init(wrappedDate: date)
+ } else {
+ return nil
+ }
+ }
+
+ public var rawValue: String {
+ OpenISO8601DateFormatter.withoutTime.string(from: normalizedWrappedDate())
+ }
+}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/swift6/OpenISO8601DateFormatter.mustache b/modules/openapi-generator/src/main/resources/swift6/OpenISO8601DateFormatter.mustache
new file mode 100644
index 000000000000..fa2335d70c3f
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/OpenISO8601DateFormatter.mustache
@@ -0,0 +1,56 @@
+//
+// OpenISO8601DateFormatter.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+// https://stackoverflow.com/a/50281094/976628
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class OpenISO8601DateFormatter: DateFormatter, @unchecked Sendable {
+ static let withoutSeconds: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.calendar = Calendar(identifier: .iso8601)
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
+ return formatter
+ }()
+
+ static let withoutTime: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.calendar = Calendar(identifier: .iso8601)
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
+ formatter.dateFormat = "yyyy-MM-dd"
+ return formatter
+ }()
+
+ private func setup() {
+ calendar = Calendar(identifier: .iso8601)
+ locale = Locale(identifier: "en_US_POSIX")
+ timeZone = TimeZone(secondsFromGMT: 0)
+ dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
+ }
+
+ override init() {
+ super.init()
+ setup()
+ }
+
+ required init?(coder aDecoder: NSCoder) {
+ super.init(coder: aDecoder)
+ setup()
+ }
+
+ override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func date(from string: String) -> Date? {
+ if let result = super.date(from: string) {
+ return result
+ } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) {
+ return result
+ }
+
+ return OpenISO8601DateFormatter.withoutTime.date(from: string)
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/Package.swift.mustache b/modules/openapi-generator/src/main/resources/swift6/Package.swift.mustache
new file mode 100644
index 000000000000..4070feca6900
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/Package.swift.mustache
@@ -0,0 +1,51 @@
+// swift-tools-version:6.0
+
+import PackageDescription
+
+let package = Package(
+ name: "{{projectName}}",
+ platforms: [
+ {{#useVapor}}
+ .macOS(.v10_15),
+ {{/useVapor}}
+ {{^useVapor}}
+ .iOS(.v12),
+ .macOS(.v10_13),
+ .tvOS(.v12),
+ .watchOS(.v4),
+ {{/useVapor}}
+ ],
+ products: [
+ // Products define the executables and libraries produced by a package, and make them visible to other packages.
+ .library(
+ name: "{{projectName}}",
+ targets: ["{{projectName}}"]
+ ),
+ ],
+ dependencies: [
+ // Dependencies declare other packages that this package depends on.
+ .package(url: "https://github.com/Flight-School/AnyCodable", .upToNextMajor(from: "0.6.7")),
+ {{#useAlamofire}}
+ .package(url: "https://github.com/Alamofire/Alamofire", .upToNextMajor(from: "5.9.1")),
+ {{/useAlamofire}}
+ {{#usePromiseKit}}
+ .package(url: "https://github.com/mxcl/PromiseKit", .upToNextMajor(from: "8.1.2")),
+ {{/usePromiseKit}}
+ {{#useRxSwift}}
+ .package(url: "https://github.com/ReactiveX/RxSwift", .upToNextMajor(from: "6.7.1")),
+ {{/useRxSwift}}
+ {{#useVapor}}
+ .package(url: "https://github.com/vapor/vapor", from: "4.0.0")
+ {{/useVapor}}
+ ],
+ targets: [
+ // Targets are the basic building blocks of a package. A target can define a module or a test suite.
+ // Targets can depend on other targets in this package, and on products in packages which this package depends on.
+ .target(
+ name: "{{projectName}}",
+ dependencies: ["AnyCodable", {{#useVapor}}"Vapor", {{/useVapor}}{{#useAlamofire}}"Alamofire", {{/useAlamofire}}{{#usePromiseKit}}"PromiseKit", {{/usePromiseKit}}{{#useRxSwift}}"RxSwift"{{/useRxSwift}}],
+ path: "{{swiftPackagePath}}{{^swiftPackagePath}}{{#useSPMFileStructure}}Sources/{{projectName}}{{/useSPMFileStructure}}{{^useSPMFileStructure}}{{projectName}}/Classes{{/useSPMFileStructure}}{{/swiftPackagePath}}"
+ ),
+ ],
+ swiftLanguageModes: [.v6]
+)
diff --git a/modules/openapi-generator/src/main/resources/swift6/Podspec.mustache b/modules/openapi-generator/src/main/resources/swift6/Podspec.mustache
new file mode 100644
index 000000000000..2eb0e324b9f0
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/Podspec.mustache
@@ -0,0 +1,39 @@
+Pod::Spec.new do |s|
+ s.name = '{{projectName}}'{{#projectDescription}}
+ s.summary = '{{.}}'{{/projectDescription}}
+ s.ios.deployment_target = '12.0'
+ s.osx.deployment_target = '10.13'
+ s.tvos.deployment_target = '12.0'
+ s.watchos.deployment_target = '4.0'
+ s.version = '{{podVersion}}{{^podVersion}}{{#apiInfo}}{{version}}{{/apiInfo}}{{^apiInfo}}}0.0.1{{/apiInfo}}{{/podVersion}}'
+ s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v{{#apiInfo}}{{version}}{{/apiInfo}}{{^apiInfo}}}0.0.1{{/apiInfo}}' }{{/podSource}}
+ {{#podAuthors}}
+ s.authors = '{{.}}'
+ {{/podAuthors}}
+ {{#podSocialMediaURL}}
+ s.social_media_url = '{{.}}'
+ {{/podSocialMediaURL}}
+ s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Proprietary'{{/podLicense}}
+ s.homepage = '{{podHomepage}}{{^podHomepage}}https://github.com/OpenAPITools/openapi-generator{{/podHomepage}}'
+ s.summary = '{{podSummary}}{{^podSummary}}{{projectName}} Swift SDK{{/podSummary}}'
+ {{#podDescription}}
+ s.description = '{{.}}'
+ {{/podDescription}}
+ {{#podScreenshots}}
+ s.screenshots = {{& podScreenshots}}
+ {{/podScreenshots}}
+ {{#podDocumentationURL}}
+ s.documentation_url = '{{.}}'
+ {{/podDocumentationURL}}
+ s.source_files = '{{swiftPackagePath}}{{^swiftPackagePath}}{{#useSPMFileStructure}}Sources/{{projectName}}{{/useSPMFileStructure}}{{^useSPMFileStructure}}{{projectName}}/Classes{{/useSPMFileStructure}}{{/swiftPackagePath}}/**/*.swift'
+ s.dependency 'AnyCodable-FlightSchool', '~> 0.6'
+ {{#useAlamofire}}
+ s.dependency 'Alamofire', '~> 5.9'
+ {{/useAlamofire}}
+ {{#usePromiseKit}}
+ s.dependency 'PromiseKit/CorePromise', '~> 8.1'
+ {{/usePromiseKit}}
+ {{#useRxSwift}}
+ s.dependency 'RxSwift', '~> 6.7'
+ {{/useRxSwift}}
+end
diff --git a/modules/openapi-generator/src/main/resources/swift6/README.mustache b/modules/openapi-generator/src/main/resources/swift6/README.mustache
new file mode 100644
index 000000000000..0cda1ab0a794
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/README.mustache
@@ -0,0 +1,84 @@
+# Swift6 API client for {{{projectName}}}
+
+{{#appDescriptionWithNewLines}}
+{{{.}}}
+{{/appDescriptionWithNewLines}}
+
+## Overview
+This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client.
+
+- API version: {{appVersion}}
+- Package version: {{packageVersion}}
+{{^hideGenerationTimestamp}}
+- Build date: {{generatedDate}}
+{{/hideGenerationTimestamp}}
+- Generator version: {{generatorVersion}}
+- Build package: {{generatorClass}}
+{{#infoUrl}}
+For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
+{{/infoUrl}}
+
+## Installation
+
+{{#useVapor}}
+Add the following entry in your Package.swift:
+
+> .package(path: "./{{{projectName}}}")
+
+{{/useVapor}}
+{{^useVapor}}
+### Carthage
+
+Run `carthage update`
+
+### CocoaPods
+
+Run `pod install`
+
+{{/useVapor}}## Documentation for API Endpoints
+
+All URIs are relative to *{{basePath}}*
+
+Class | Method | HTTP request | Description
+------------ | ------------- | ------------- | -------------
+{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{summary}}
+{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
+
+## Documentation For Models
+
+{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md)
+{{/model}}{{/models}}
+
+
+## Documentation For Authorization
+
+{{^authMethods}}Endpoints do not require authorization.{{/authMethods}}
+{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}}
+{{#authMethods}}
+
+### {{name}}
+
+{{#isApiKey}}- **Type**: API key
+- **API key parameter name**: {{{keyParamName}}}
+- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
+{{/isApiKey}}
+{{#isBasicBasic}}- **Type**: HTTP basic authentication
+{{/isBasicBasic}}
+{{#isBasicBearer}}- **Type**: HTTP Bearer Token authentication{{#bearerFormat}} ({{{.}}}){{/bearerFormat}}
+{{/isBasicBearer}}
+{{#isHttpSignature}}- **Type**: HTTP signature authentication
+{{/isHttpSignature}}
+{{#isOAuth}}- **Type**: OAuth
+- **Flow**: {{{flow}}}
+- **Authorization URL**: {{{authorizationUrl}}}
+- **Scopes**: {{^scopes}}N/A{{/scopes}}
+{{#scopes}} - **{{{scope}}}**: {{{description}}}
+{{/scopes}}
+{{/isOAuth}}
+
+{{/authMethods}}
+
+## Author
+
+{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}}
+{{/-last}}{{/apis}}{{/apiInfo}}
diff --git a/modules/openapi-generator/src/main/resources/swift6/SynchronizedDictionary.mustache b/modules/openapi-generator/src/main/resources/swift6/SynchronizedDictionary.mustache
new file mode 100644
index 000000000000..acf7ff4031bd
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/SynchronizedDictionary.mustache
@@ -0,0 +1,36 @@
+// SynchronizedDictionary.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+internal struct SynchronizedDictionary {
+
+ private var dictionary = [K: V]()
+ private let queue = DispatchQueue(
+ label: "SynchronizedDictionary",
+ qos: DispatchQoS.userInitiated,
+ attributes: [DispatchQueue.Attributes.concurrent],
+ autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
+ target: nil
+ )
+
+ internal subscript(key: K) -> V? {
+ get {
+ var value: V?
+
+ queue.sync {
+ value = self.dictionary[key]
+ }
+
+ return value
+ }
+ set {
+ queue.sync(flags: DispatchWorkItemFlags.barrier) {
+ self.dictionary[key] = newValue
+ }
+ }
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/Validation.mustache b/modules/openapi-generator/src/main/resources/swift6/Validation.mustache
new file mode 100644
index 000000000000..1197e79dfd70
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/Validation.mustache
@@ -0,0 +1,161 @@
+// Validation.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct StringRule: @unchecked Sendable {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var minLength: Int?
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var maxLength: Int?
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var pattern: String?
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct NumericRule: @unchecked Sendable {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var minimum: T?
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var exclusiveMinimum = false
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var maximum: T?
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var exclusiveMaximum = false
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var multipleOf: T?
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct ArrayRule: @unchecked Sendable {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var minItems: Int?
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var maxItems: Int?
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var uniqueItems: Bool
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum StringValidationErrorKind: Error {
+ case minLength, maxLength, pattern
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum NumericValidationErrorKind: Error {
+ case minimum, maximum, multipleOf
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum ArrayValidationErrorKind: Error {
+ case minItems, maxItems, uniqueItems
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct ValidationError: Error {
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} fileprivate(set) var kinds: Set
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct Validator {
+ /// Validate a string against a rule.
+ /// - Parameter string: The String you wish to validate.
+ /// - Parameter rule: The StringRule you wish to use for validation.
+ /// - Returns: A validated string.
+ /// - Throws: `ValidationError` if the string is invalid against the rule,
+ /// `NSError` if the rule.pattern is invalid.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func validate(_ string: String, against rule: StringRule) throws -> String {
+ var error = ValidationError(kinds: [])
+ if let minLength = rule.minLength, !(minLength <= string.count) {
+ error.kinds.insert(.minLength)
+ }
+ if let maxLength = rule.maxLength, !(string.count <= maxLength) {
+ error.kinds.insert(.maxLength)
+ }
+ if let pattern = rule.pattern {
+ let matches = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
+ .matches(in: string, range: .init(location: 0, length: string.utf16.count))
+ if matches.isEmpty {
+ error.kinds.insert(.pattern)
+ }
+ }
+ guard error.kinds.isEmpty else {
+ throw error
+ }
+ return string
+ }
+
+ /// Validate a integer against a rule.
+ /// - Parameter numeric: The integer you wish to validate.
+ /// - Parameter rule: The NumericRule you wish to use for validation.
+ /// - Returns: A validated integer.
+ /// - Throws: `ValidationError` if the numeric is invalid against the rule.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func validate(_ numeric: T, against rule: NumericRule) throws -> T {
+ var error = ValidationError(kinds: [])
+ if let minium = rule.minimum {
+ if !rule.exclusiveMinimum, minium > numeric {
+ error.kinds.insert(.minimum)
+ }
+ if rule.exclusiveMinimum, minium >= numeric {
+ error.kinds.insert(.minimum)
+ }
+ }
+ if let maximum = rule.maximum {
+ if !rule.exclusiveMaximum, numeric > maximum {
+ error.kinds.insert(.maximum)
+ }
+ if rule.exclusiveMaximum, numeric >= maximum {
+ error.kinds.insert(.maximum)
+ }
+ }
+ if let multipleOf = rule.multipleOf, !numeric.isMultiple(of: multipleOf) {
+ error.kinds.insert(.multipleOf)
+ }
+ guard error.kinds.isEmpty else {
+ throw error
+ }
+ return numeric
+ }
+
+ /// Validate a fractional number against a rule.
+ /// - Parameter numeric: The fractional number you wish to validate.
+ /// - Parameter rule: The NumericRule you wish to use for validation.
+ /// - Returns: A validated fractional number.
+ /// - Throws: `ValidationError` if the numeric is invalid against the rule.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func validate(_ numeric: T, against rule: NumericRule) throws -> T {
+ var error = ValidationError(kinds: [])
+ if let minium = rule.minimum {
+ if !rule.exclusiveMinimum, minium > numeric {
+ error.kinds.insert(.minimum)
+ }
+ if rule.exclusiveMinimum, minium >= numeric {
+ error.kinds.insert(.minimum)
+ }
+ }
+ if let maximum = rule.maximum {
+ if !rule.exclusiveMaximum, numeric > maximum {
+ error.kinds.insert(.maximum)
+ }
+ if rule.exclusiveMaximum, numeric >= maximum {
+ error.kinds.insert(.maximum)
+ }
+ }
+ if let multipleOf = rule.multipleOf, numeric.remainder(dividingBy: multipleOf) != 0 {
+ error.kinds.insert(.multipleOf)
+ }
+ guard error.kinds.isEmpty else {
+ throw error
+ }
+ return numeric
+ }
+
+ /// Validate a array against a rule.
+ /// - Parameter array: The Array you wish to validate.
+ /// - Parameter rule: The ArrayRule you wish to use for validation.
+ /// - Returns: A validated array.
+ /// - Throws: `ValidationError` if the string is invalid against the rule.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func validate(_ array: Array, against rule: ArrayRule) throws -> Array {
+ var error = ValidationError(kinds: [])
+ if let minItems = rule.minItems, !(minItems <= array.count) {
+ error.kinds.insert(.minItems)
+ }
+ if let maxItems = rule.maxItems, !(array.count <= maxItems) {
+ error.kinds.insert(.maxItems)
+ }
+ if rule.uniqueItems {
+ let unique = Set(array)
+ if unique.count != array.count {
+ error.kinds.insert(.uniqueItems)
+ }
+ }
+ guard error.kinds.isEmpty else {
+ throw error
+ }
+ return array
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/XcodeGen.mustache b/modules/openapi-generator/src/main/resources/swift6/XcodeGen.mustache
new file mode 100644
index 000000000000..d4a36d58ee04
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/XcodeGen.mustache
@@ -0,0 +1,18 @@
+name: {{projectName}}
+targets:
+ {{projectName}}:
+ type: framework
+ platform: iOS
+ deploymentTarget: "11.0"
+ sources: [{{swiftPackagePath}}{{^swiftPackagePath}}{{#useSPMFileStructure}}Sources{{/useSPMFileStructure}}{{^useSPMFileStructure}}{{projectName}}{{/useSPMFileStructure}}{{/swiftPackagePath}}]
+ info:
+ path: ./Info.plist
+ version: {{podVersion}}{{^podVersion}}{{#apiInfo}}{{version}}{{/apiInfo}}{{^apiInfo}}}0.0.1{{/apiInfo}}{{/podVersion}}
+ settings:
+ APPLICATION_EXTENSION_API_ONLY: true
+ scheme: {}
+ dependencies:
+ - carthage: AnyCodable{{#useAlamofire}}
+ - carthage: Alamofire{{/useAlamofire}}{{#usePromiseKit}}
+ - carthage: PromiseKit{{/usePromiseKit}}{{#useRxSwift}}
+ - carthage: RxSwift{{/useRxSwift}}
diff --git a/modules/openapi-generator/src/main/resources/swift6/_param.mustache b/modules/openapi-generator/src/main/resources/swift6/_param.mustache
new file mode 100644
index 000000000000..00b0c399c636
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/_param.mustache
@@ -0,0 +1 @@
+"{{baseName}}": {{#isQueryParam}}(wrappedValue: {{/isQueryParam}}{{paramName}}{{^required}}?{{/required}}.encodeToJSON(){{#isQueryParam}}, isExplode: {{isExplode}}){{/isQueryParam}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/swift6/api.mustache b/modules/openapi-generator/src/main/resources/swift6/api.mustache
new file mode 100644
index 000000000000..5626dae3188c
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/api.mustache
@@ -0,0 +1,466 @@
+{{#operations}}//
+// {{classname}}.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation{{#usePromiseKit}}
+@preconcurrency import PromiseKit{{/usePromiseKit}}{{#useRxSwift}}
+@preconcurrency import RxSwift{{/useRxSwift}}{{#useCombine}}
+#if canImport(Combine)
+import Combine
+#endif{{/useCombine}}{{#useVapor}}
+import Vapor{{/useVapor}}
+#if canImport(AnyCodable)
+import AnyCodable
+#endif{{#swiftUseApiNamespace}}
+
+extension {{projectName}}API {
+{{/swiftUseApiNamespace}}
+
+{{#description}}
+/** {{{.}}} */{{/description}}
+{{#objcCompatible}}@objcMembers {{/objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{classname}}{{#objcCompatible}} : NSObject{{/objcCompatible}} {
+{{^apiStaticMethod}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init() {}
+{{/apiStaticMethod}}
+{{#operation}}
+ {{#allParams}}
+ {{#isEnum}}
+
+ /**
+ * enum for parameter {{paramName}}
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}_{{operationId}}: {{^isContainer}}{{{dataType}}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, CaseIterable{{#useVapor}}, Content{{/useVapor}} {
+ {{^enumUnknownDefaultCase}}
+ {{#allowableValues}}
+ {{#enumVars}}
+ case {{name}} = {{{value}}}
+ {{/enumVars}}
+ {{/allowableValues}}
+ {{/enumUnknownDefaultCase}}
+ {{#enumUnknownDefaultCase}}
+ {{#allowableValues}}
+ {{#enumVars}}
+ {{^-last}}
+ case {{name}} = {{{value}}}
+ {{/-last}}
+ {{/enumVars}}
+ {{/allowableValues}}
+ {{/enumUnknownDefaultCase}}
+ }
+ {{/isEnum}}
+ {{/allParams}}
+{{^useVapor}}
+{{^usePromiseKit}}
+{{^useRxSwift}}
+{{^useResult}}
+{{^useCombine}}
+{{^useAsyncAwait}}
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}{{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ @discardableResult
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void) -> RequestTask {
+ return {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in
+ switch result {
+ {{#returnType}}
+ case let .success(response):
+ completion(response.body, nil)
+ {{/returnType}}
+ {{^returnType}}
+ case .success:
+ completion((), nil)
+ {{/returnType}}
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+{{/useAsyncAwait}}
+{{/useCombine}}
+{{/useResult}}
+{{/useRxSwift}}
+{{/usePromiseKit}}
+{{/useVapor}}
+{{#usePromiseKit}}
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}{{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
+ - returns: Promise<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
+ */
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Promise<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
+ let deferred = Promise<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.pending()
+ {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute { result in
+ switch result {
+ {{#returnType}}
+ case let .success(response):
+ deferred.resolver.fulfill(response.body)
+ {{/returnType}}
+ {{^returnType}}
+ case .success:
+ deferred.resolver.fulfill(())
+ {{/returnType}}
+ case let .failure(error):
+ deferred.resolver.reject(error)
+ }
+ }
+ return deferred.promise
+ }
+{{/usePromiseKit}}
+{{#useRxSwift}}
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}{{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - returns: Observable<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}>
+ */
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.shared.apiResponseQueue) -> Observable<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
+ return Observable.create { observer -> Disposable in
+ let requestTask = self.{{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in
+ switch result {
+ {{#returnType}}
+ case let .success(response):
+ observer.onNext(response.body)
+ {{/returnType}}
+ {{^returnType}}
+ case .success:
+ observer.onNext(())
+ {{/returnType}}
+ case let .failure(error):
+ observer.onError(error)
+ }
+ observer.onCompleted()
+ }
+
+ return Disposables.create {
+ requestTask.cancel()
+ }
+ }
+ }
+{{/useRxSwift}}
+{{#useCombine}}
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}{{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
+ - returns: AnyPublisher<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error>
+ */
+ #if canImport(Combine)
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> AnyPublisher<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error> {
+ let requestBuilder = {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}})
+ let requestTask = requestBuilder.requestTask
+ return {{#combineDeferred}}Deferred { {{/combineDeferred}}Future<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}, Error> { promise in
+ nonisolated(unsafe) let promise = promise
+ requestBuilder.execute { result in
+ switch result {
+ {{#returnType}}
+ case let .success(response):
+ promise(.success(response.body))
+ {{/returnType}}
+ {{^returnType}}
+ case .success:
+ promise(.success(()))
+ {{/returnType}}
+ case let .failure(error):
+ promise(.failure(error))
+ }
+ }
+ }
+ .handleEvents(receiveCancel: {
+ requestTask.cancel()
+ })
+ .eraseToAnyPublisher()
+ {{#combineDeferred}}
+ }
+ .eraseToAnyPublisher()
+ {{/combineDeferred}}
+ }
+ #endif
+{{/useCombine}}
+{{#useAsyncAwait}}
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}{{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
+ - returns: {{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}
+ */
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) async throws(ErrorResponse){{#returnType}} -> {{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{/returnType}} {
+ return try await {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute().body
+ }
+{{/useAsyncAwait}}
+{{#useResult}}
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}{{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the result
+ */
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ @discardableResult
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.shared.apiResponseQueue, completion: @Sendable @escaping (_ result: Swift.Result<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}, ErrorResponse>) -> Void) -> RequestTask {
+ return {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in
+ switch result {
+ {{#returnType}}
+ case let .success(response):
+ completion(.success(response.body))
+ {{/returnType}}
+ {{^returnType}}
+ case .success:
+ completion(.success(()))
+ {{/returnType}}
+ case let .failure(error):
+ completion(.failure(error))
+ }
+ }
+ }
+{{/useResult}}
+{{#useVapor}}
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}
+ {{httpMethod}} {{{path}}}{{#notes}}
+ {{{.}}}{{/notes}}{{#subresourceOperation}}
+ subresourceOperation: {{.}}{{/subresourceOperation}}{{#defaultResponse}}
+ defaultResponse: {{.}}{{/defaultResponse}}
+ {{#authMethods}}
+ - {{#isBasicBasic}}BASIC{{/isBasicBasic}}{{#isBasicBearer}}Bearer Token{{/isBasicBearer}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}:
+ - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeader}}(HEADER){{/isKeyInHeader}}{{/keyParamName}}
+ - name: {{name}}
+ {{/authMethods}}
+ {{#hasResponseHeaders}}
+ - responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{dataType}}}){{^-last}}, {{/-last}}{{/responseHeaders}}]
+ {{/hasResponseHeaders}}
+ {{#externalDocs}}
+ - externalDocs: {{.}}
+ {{/externalDocs}}
+ {{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
+ {{/allParams}}
+ - returns: `EventLoopFuture` of `ClientResponse` {{{description}}}
+ */
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}Raw({{#allParams}}{{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}API.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture {
+ {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{#-first}}var{{/-first}}{{/pathParams}} localVariablePath = "{{{path}}}"{{#pathParams}}
+ let {{paramName}}PreEscape = String(describing: {{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}{{paramName}}{{/isEnum}})
+ let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}}
+ let localVariableURLString = {{projectName}}API.shared.basePath + localVariablePath
+
+ guard let localVariableApiClient = {{#swiftUseApiNamespace}}{{projectName}}API.{{/swiftUseApiNamespace}}{{projectName}}API.shared.apiClient else {
+ fatalError("{{projectName}}API.shared.apiClient is not set.")
+ }
+
+ return localVariableApiClient.send(.{{httpMethod}}, headers: headers, to: URI(string: localVariableURLString)) { localVariableRequest in
+ try {{#swiftUseApiNamespace}}{{projectName}}API.{{/swiftUseApiNamespace}}Configuration.apiWrapper(&localVariableRequest)
+ {{#hasHeaderParams}}{{#headerParams}}
+ localVariableRequest.headers.add(name: "{{baseName}}", value: {{#isArray}}{{paramName}}{{^required}}?{{/required}}.map { $0{{#isEnum}}.rawValue{{/isEnum}}.description }.description{{/isArray}}{{^isArray}}{{#isEnum}}{{paramName}}{{^required}}?{{/required}}.rawValue.description{{/isEnum}}{{^isEnum}}{{paramName}}{{^required}}?{{/required}}.description{{/isEnum}}{{/isArray}}{{^required}} ?? ""{{/required}})
+ {{/headerParams}}{{/hasHeaderParams}}
+ {{#hasQueryParams}}struct QueryParams: Content {
+ {{#queryParams}}
+ var {{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}}
+ {{/queryParams}}
+
+ enum CodingKeys: String, CodingKey {
+ {{#queryParams}}
+ case {{paramName}}{{#baseName}} = "{{.}}"{{/baseName}}
+ {{/queryParams}}
+ }
+ }
+ try localVariableRequest.query.encode(QueryParams({{#queryParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/queryParams}})){{/hasQueryParams}}
+ {{#hasBodyParam}}
+ {{#bodyParam}}{{#required}}{{#isBinary}}localVariableRequest.body = ByteBuffer(data: {{paramName}}){{/isBinary}}{{^isBinary}}{{#isFile}}localVariableRequest.body = ByteBuffer(data: {{paramName}}){{/isFile}}try localVariableRequest.content.encode({{paramName}}, using: {{projectName}}API.shared.contentConfiguration.requireEncoder(for: {{{dataType}}}.defaultContentType)){{/isBinary}}{{/required}}{{^required}}if let localVariableBody = {{paramName}} {
+ {{#isBinary}}localVariableRequest.body = ByteBuffer(data: localVariableBody){{/isBinary}}{{^isBinary}}{{#isFile}}localVariableRequest.body = ByteBuffer(data: localVariableBody){{/isFile}}try localVariableRequest.content.encode(localVariableBody, using: {{projectName}}API.shared.contentConfiguration.requireEncoder(for: {{{dataType}}}.defaultContentType)){{/isBinary}}
+ }{{/required}}{{/bodyParam}}
+ {{/hasBodyParam}}
+ {{#hasFormParams}}struct FormParams: Content {
+ static let defaultContentType = Vapor.HTTPMediaType.formData
+ {{#formParams}}
+ var {{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}}
+ {{/formParams}}
+ }
+ try localVariableRequest.content.encode(FormParams({{#formParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/formParams}}), using: {{projectName}}API.shared.contentConfiguration.requireEncoder(for: FormParams.defaultContentType)){{/hasFormParams}}
+ try beforeSend(&localVariableRequest)
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}} {
+ {{#responses}}
+ case http{{code}}({{#dataType}}value: {{{.}}}, {{/dataType}}raw: ClientResponse)
+ {{/responses}}
+ {{^hasDefaultResponse}}
+ case http0(raw: ClientResponse)
+ {{/hasDefaultResponse}}
+ }
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}
+ {{httpMethod}} {{{path}}}{{#notes}}
+ {{{.}}}{{/notes}}{{#subresourceOperation}}
+ subresourceOperation: {{.}}{{/subresourceOperation}}{{#defaultResponse}}
+ defaultResponse: {{.}}{{/defaultResponse}}
+ {{#authMethods}}
+ - {{#isBasicBasic}}BASIC{{/isBasicBasic}}{{#isBasicBearer}}Bearer Token{{/isBasicBearer}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}:
+ - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeader}}(HEADER){{/isKeyInHeader}}{{/keyParamName}}
+ - name: {{name}}
+ {{/authMethods}}
+ {{#hasResponseHeaders}}
+ - responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{dataType}}}){{^-last}}, {{/-last}}{{/responseHeaders}}]
+ {{/hasResponseHeaders}}
+ {{#externalDocs}}
+ - externalDocs: {{.}}
+ {{/externalDocs}}
+ {{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
+ {{/allParams}}
+ - returns: `EventLoopFuture` of `{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}` {{{description}}}
+ */
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isArray}}[{{enumName}}_{{operationId}}]{{/isArray}}{{^isArray}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}API.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}> {
+ return {{operationId}}Raw({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: headers, beforeSend: beforeSend).flatMapThrowing { response -> {{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}} in
+ switch response.status.code {
+ {{#responses}}
+ {{#isDefault}}default{{/isDefault}}{{^isDefault}}case {{code}}{{/isDefault}}:
+ return .http{{code}}({{#dataType}}value: {{#isBinary}}Data(buffer: response.body ?? ByteBuffer()){{/isBinary}}{{^isBinary}}{{#isFile}}Data(buffer: response.body ?? ByteBuffer()){{/isFile}}{{^isFile}}try response.content.decode({{{dataType}}}.self, using: {{projectName}}API.shared.contentConfiguration.requireDecoder(for: {{{dataType}}}.defaultContentType)){{/isFile}}{{/isBinary}}, {{/dataType}}raw: response)
+ {{/responses}}
+ {{^hasDefaultResponse}}
+ default:
+ return .http0(raw: response)
+ {{/hasDefaultResponse}}
+ }
+ }
+ }
+{{/useVapor}}
+{{^useVapor}}
+
+ /**
+ {{#summary}}
+ {{{.}}}
+ {{/summary}}
+ - {{httpMethod}} {{{path}}}{{#notes}}
+ - {{{.}}}{{/notes}}{{#subresourceOperation}}
+ - subresourceOperation: {{.}}{{/subresourceOperation}}{{#defaultResponse}}
+ - defaultResponse: {{.}}{{/defaultResponse}}
+ {{#authMethods}}
+ - {{#isBasicBasic}}BASIC{{/isBasicBasic}}{{#isBasicBearer}}Bearer Token{{/isBasicBearer}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}:
+ - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeader}}(HEADER){{/isKeyInHeader}}{{/keyParamName}}
+ - name: {{name}}
+ {{/authMethods}}
+ {{#hasResponseHeaders}}
+ - responseHeaders: [{{#responseHeaders}}{{{baseName}}}({{{dataType}}}){{^-last}}, {{/-last}}{{/responseHeaders}}]
+ {{/hasResponseHeaders}}
+ {{#externalDocs}}
+ - externalDocs: {{.}}
+ {{/externalDocs}}
+ {{#allParams}}
+ - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}
+ {{/allParams}}
+ - returns: RequestBuilder<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}}
+ */
+ {{#isDeprecated}}
+ @available(*, deprecated, message: "This operation is deprecated.")
+ {{/isDeprecated}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} {{#apiStaticMethod}}class {{/apiStaticMethod}}func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> RequestBuilder<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {
+ {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{#-first}}var{{/-first}}{{/pathParams}} localVariablePath = "{{{path}}}"{{#pathParams}}
+ let {{paramName}}PreEscape = "\({{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}APIHelper.mapValueToPathItem({{paramName}}){{/isEnum}})"
+ let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}}
+ let localVariableURLString = {{projectName}}API.shared.basePath + localVariablePath
+ {{#bodyParam}}
+ {{#isBinary}}
+ let localVariableParameters = ["body": {{paramName}}]
+ {{/isBinary}}
+ {{^isBinary}}
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: {{paramName}})
+ {{/isBinary}}
+ {{/bodyParam}}
+ {{^bodyParam}}
+ {{#hasFormParams}}
+ let localVariableFormParams: [String: Any?] = [
+ {{#formParams}}
+ {{> _param}},
+ {{/formParams}}
+ ]
+
+ let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
+ let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
+ {{/hasFormParams}}
+ {{^hasFormParams}}
+ let localVariableParameters: [String: Any]? = nil
+ {{/hasFormParams}}
+{{/bodyParam}}{{#hasQueryParams}}
+ var localVariableUrlComponents = URLComponents(string: localVariableURLString)
+ localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([{{^queryParams}}:{{/queryParams}}
+ {{#queryParams}}
+ {{> _param}},
+ {{/queryParams}}
+ ]){{/hasQueryParams}}{{^hasQueryParams}}
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString){{/hasQueryParams}}
+
+ let localVariableNillableHeaders: [String: Any?] = [{{^headerParams}}{{^hasFormParams}}{{^hasConsumes}}
+ :{{/hasConsumes}}{{/hasFormParams}}{{/headerParams}}{{#hasFormParams}}
+ "Content-Type": {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}},{{/hasFormParams}}{{^hasFormParams}}{{#hasConsumes}}
+ "Content-Type": {{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}},{{/hasConsumes}}{{/hasFormParams}}{{#headerParams}}
+ {{> _param}},{{/headerParams}}
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder<{{{returnType}}}{{#returnType}}{{#isResponseOptional}}?{{/isResponseOptional}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.shared.requestBuilderFactory.{{#returnType}}getBuilder(){{/returnType}}{{^returnType}}getNonDecodableBuilder(){{/returnType}}
+
+ return localVariableRequestBuilder.init(method: "{{httpMethod}}", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: {{#hasAuthMethods}}true{{/hasAuthMethods}}{{^hasAuthMethods}}false{{/hasAuthMethods}})
+ }
+{{/useVapor}}
+{{/operation}}
+}
+{{#swiftUseApiNamespace}}
+}
+{{/swiftUseApiNamespace}}
+{{/operations}}
diff --git a/modules/openapi-generator/src/main/resources/swift6/api_doc.mustache b/modules/openapi-generator/src/main/resources/swift6/api_doc.mustache
new file mode 100644
index 000000000000..7faccc1a1d8f
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/api_doc.mustache
@@ -0,0 +1,141 @@
+# {{classname}}{{#description}}
+{{.}}{{/description}}
+
+All URIs are relative to *{{{basePath}}}*
+
+Method | HTTP request | Description
+------------- | ------------- | -------------
+{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{summary}}
+{{/operation}}{{/operations}}
+
+{{#operations}}
+{{#operation}}
+# **{{{operationId}}}**
+```swift
+{{^usePromiseKit}}
+{{^useRxSwift}}
+{{^useVapor}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping (_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)
+{{/useVapor}}
+{{/useRxSwift}}
+{{/usePromiseKit}}
+{{#usePromiseKit}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}>
+{{/usePromiseKit}}
+{{#useRxSwift}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}>
+{{/useRxSwift}}
+{{#useVapor}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}API.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}>
+{{/useVapor}}
+```
+
+{{{summary}}}{{#notes}}
+
+{{{.}}}{{/notes}}
+
+### Example
+```swift
+// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new
+import {{{projectName}}}
+
+{{#allParams}}let {{paramName}} = {{{vendorExtensions.x-swift-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}}
+{{/allParams}}
+
+{{^usePromiseKit}}
+{{^useRxSwift}}
+{{^useVapor}}
+{{#summary}}
+// {{{.}}}
+{{/summary}}
+{{classname}}.{{{operationId}}}({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) { (response, error) in
+ guard error == nil else {
+ print(error)
+ return
+ }
+
+ if (response) {
+ dump(response)
+ }
+}
+{{/useVapor}}
+{{/useRxSwift}}
+{{/usePromiseKit}}
+{{#usePromiseKit}}
+{{#summary}}
+// {{{.}}}
+{{/summary}}
+{{classname}}.{{{operationId}}}({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).then {
+ // when the promise is fulfilled
+ }.always {
+ // regardless of whether the promise is fulfilled, or rejected
+ }.catch { errorType in
+ // when the promise is rejected
+}
+{{/usePromiseKit}}
+{{#useRxSwift}}
+// TODO RxSwift sample code not yet implemented. To contribute, please open a ticket via http://github.com/OpenAPITools/openapi-generator/issues/new
+{{/useRxSwift}}
+{{#useVapor}}
+{{#summary}}
+// {{{.}}}
+{{/summary}}
+{{classname}}.{{{operationId}}}({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).whenComplete { result in
+ switch result {
+ case .failure(let error):
+ // process error
+ case .success(let response):
+ switch response {
+ // process decoded response value or raw ClientResponse
+ {{#responses}}
+ case .http{{code}}(let value, let raw):
+ {{/responses}}
+ {{^hasDefaultResponse}}
+ case .http0(let value, let raw):
+ {{/hasDefaultResponse}}
+ }
+ }
+}
+{{/useVapor}}
+```
+
+### Parameters
+{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
+Name | Type | Description | Notes
+------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
+{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{.}}]{{/defaultValue}}
+{{/allParams}}
+
+### Return type
+
+{{#useVapor}}
+#### {{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}
+
+```swift
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}} {
+ {{#responses}}
+ case http{{code}}(value: {{#dataType}}{{.}}?{{/dataType}}{{^dataType}}Void?{{/dataType}}, raw: ClientResponse)
+ {{/responses}}
+ {{^hasDefaultResponse}}
+ case http0(value: {{#returnType}}{{.}}?{{/returnType}}{{^returnType}}Void?{{/returnType}}, raw: ClientResponse)
+ {{/hasDefaultResponse}}
+}
+```
+{{/useVapor}}
+{{^useVapor}}
+{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}Void (empty response body){{/returnType}}
+{{/useVapor}}
+
+### Authorization
+
+{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}}
+
+### HTTP request headers
+
+ - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
+ - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}}
+
+[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
+
+{{/operation}}
+{{/operations}}
diff --git a/modules/openapi-generator/src/main/resources/swift6/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/swift6/git_push.sh.mustache
new file mode 100755
index 000000000000..0e3776ae6dd4
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/git_push.sh.mustache
@@ -0,0 +1,57 @@
+#!/bin/sh
+# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
+#
+# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com"
+
+git_user_id=$1
+git_repo_id=$2
+release_note=$3
+git_host=$4
+
+if [ "$git_host" = "" ]; then
+ git_host="{{{gitHost}}}"
+ echo "[INFO] No command line input provided. Set \$git_host to $git_host"
+fi
+
+if [ "$git_user_id" = "" ]; then
+ git_user_id="{{{gitUserId}}}"
+ echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
+fi
+
+if [ "$git_repo_id" = "" ]; then
+ git_repo_id="{{{gitRepoId}}}"
+ echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
+fi
+
+if [ "$release_note" = "" ]; then
+ release_note="{{{releaseNote}}}"
+ echo "[INFO] No command line input provided. Set \$release_note to $release_note"
+fi
+
+# Initialize the local directory as a Git repository
+git init
+
+# Adds the files in the local repository and stages them for commit.
+git add .
+
+# Commits the tracked changes and prepares them to be pushed to a remote repository.
+git commit -m "$release_note"
+
+# Sets the new remote
+git_remote=$(git remote)
+if [ "$git_remote" = "" ]; then # git remote not defined
+
+ if [ "$GIT_TOKEN" = "" ]; then
+ echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
+ git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
+ else
+ git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git
+ fi
+
+fi
+
+git pull origin master
+
+# Pushes (Forces) the changes in the local repository up to the remote repository
+echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
+git push origin master 2>&1 | grep -v 'To https'
diff --git a/modules/openapi-generator/src/main/resources/swift6/gitignore.mustache b/modules/openapi-generator/src/main/resources/swift6/gitignore.mustache
new file mode 100644
index 000000000000..316a84507fb4
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/gitignore.mustache
@@ -0,0 +1,100 @@
+# Created by https://www.toptal.com/developers/gitignore/api/xcode,swift
+# Edit at https://www.toptal.com/developers/gitignore?templates=xcode,swift
+
+### Swift ###
+# Xcode
+#
+# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
+
+## User settings
+xcuserdata/
+
+## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
+*.xcscmblueprint
+*.xccheckout
+
+## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
+build/
+DerivedData/
+*.moved-aside
+*.pbxuser
+!default.pbxuser
+*.mode1v3
+!default.mode1v3
+*.mode2v3
+!default.mode2v3
+*.perspectivev3
+!default.perspectivev3
+
+## Obj-C/Swift specific
+*.hmap
+
+## App packaging
+*.ipa
+*.dSYM.zip
+*.dSYM
+
+## Playgrounds
+timeline.xctimeline
+playground.xcworkspace
+
+# Swift Package Manager
+# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
+# Packages/
+# Package.pins
+# Package.resolved
+# *.xcodeproj
+# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
+# hence it is not needed unless you have added a package configuration file to your project
+# .swiftpm
+
+.build/
+
+# CocoaPods
+# We recommend against adding the Pods directory to your .gitignore. However
+# you should judge for yourself, the pros and cons are mentioned at:
+# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
+# Pods/
+# Add this line if you want to avoid checking in source code from the Xcode workspace
+# *.xcworkspace
+
+# Carthage
+# Add this line if you want to avoid checking in source code from Carthage dependencies.
+# Carthage/Checkouts
+
+Carthage/Build/
+
+# Accio dependency management
+Dependencies/
+.accio/
+
+# fastlane
+# It is recommended to not store the screenshots in the git repo.
+# Instead, use fastlane to re-generate the screenshots whenever they are needed.
+# For more information about the recommended setup visit:
+# https://docs.fastlane.tools/best-practices/source-control/#source-control
+
+fastlane/report.xml
+fastlane/Preview.html
+fastlane/screenshots/**/*.png
+fastlane/test_output
+
+# Code Injection
+# After new code Injection tools there's a generated folder /iOSInjectionProject
+# https://github.com/johnno1962/injectionforxcode
+
+iOSInjectionProject/
+
+### Xcode ###
+
+## Xcode 8 and earlier
+
+### Xcode Patch ###
+*.xcodeproj/*
+!*.xcodeproj/project.pbxproj
+!*.xcodeproj/xcshareddata/
+!*.xcworkspace/contents.xcworkspacedata
+/*.gcno
+**/xcshareddata/WorkspaceSettings.xcsettings
+
+# End of https://www.toptal.com/developers/gitignore/api/xcode,swift
diff --git a/modules/openapi-generator/src/main/resources/swift6/libraries/alamofire/AlamofireImplementations.mustache b/modules/openapi-generator/src/main/resources/swift6/libraries/alamofire/AlamofireImplementations.mustache
new file mode 100644
index 000000000000..71610c7b4bcd
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/libraries/alamofire/AlamofireImplementations.mustache
@@ -0,0 +1,418 @@
+// AlamofireImplementations.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+import Alamofire
+
+class AlamofireRequestBuilderFactory: RequestBuilderFactory {
+ func getNonDecodableBuilder() -> RequestBuilder.Type {
+ return AlamofireRequestBuilder.self
+ }
+
+ func getBuilder() -> RequestBuilder.Type {
+ return AlamofireDecodableRequestBuilder.self
+ }
+}
+
+fileprivate class AlamofireRequestBuilderConfiguration: @unchecked Sendable {
+ private init() {}
+ static let shared = AlamofireRequestBuilderConfiguration()
+
+ // Store manager to retain its reference
+ var managerStore = SynchronizedDictionary()
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class AlamofireRequestBuilder: RequestBuilder, @unchecked Sendable {
+ required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
+ super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication)
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the session
+ configuration.
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createAlamofireSession(interceptor: RequestInterceptor? = nil) -> Alamofire.Session {
+ let configuration = URLSessionConfiguration.default
+ configuration.httpAdditionalHeaders = buildHeaders()
+ return Alamofire.Session(configuration: configuration,
+ interceptor: interceptor)
+ }
+
+ /**
+ May be overridden by a subclass if you want to custom request constructor.
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createURLRequest() -> URLRequest? {
+ let xMethod = Alamofire.HTTPMethod(rawValue: method)
+
+ let encoding: ParameterEncoding
+
+ switch xMethod {
+ case .get, .head:
+ encoding = URLEncoding()
+
+ case .options, .post, .put, .patch, .delete, .trace, .connect:
+ encoding = JSONDataEncoding()
+
+ default:
+ fatalError("Unsupported HTTPMethod - \(xMethod.rawValue)")
+ }
+
+ guard let originalRequest = try? URLRequest(url: URLString, method: xMethod, headers: HTTPHeaders(buildHeaders())) else { return nil }
+ return try? encoding.encode(originalRequest, with: parameters)
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the Content-Type
+ that is given to an uploaded form part.
+
+ Return nil to use the default behavior (inferring the Content-Type from
+ the file extension). Return the desired Content-Type otherwise.
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func contentTypeForFormPart(fileURL: URL) -> String? {
+ return nil
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the request
+ configuration (e.g. to override the cache policy).
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func makeRequest(manager: Session, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest {
+ return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: HTTPHeaders(headers))
+ }
+
+ @discardableResult
+ override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.shared.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> RequestTask {
+ let managerId = UUID().uuidString
+ // Create a new manager for each request to customize its request header
+ let manager = createAlamofireSession()
+ AlamofireRequestBuilderConfiguration.shared.managerStore[managerId] = manager
+
+ let xMethod = Alamofire.HTTPMethod(rawValue: method)
+
+ let encoding: ParameterEncoding?
+
+ switch xMethod {
+ case .get, .head:
+ encoding = URLEncoding()
+
+ case .options, .post, .put, .patch, .delete, .trace, .connect:
+ let contentType = headers["Content-Type"] ?? "application/json"
+
+ if contentType.hasPrefix("application/") && contentType.contains("json") {
+ encoding = JSONDataEncoding()
+ } else if contentType.hasPrefix("multipart/form-data") {
+ encoding = nil
+
+ let upload = manager.upload(multipartFormData: { mpForm in
+ for (k, v) in self.parameters! {
+ for v in (v as? Array ?? [v]) {
+ switch v {
+ case let fileURL as URL:
+ if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) {
+ mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType)
+ } else {
+ mpForm.append(fileURL, withName: k)
+ }
+ case let string as String:
+ mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k)
+ case let number as NSNumber:
+ mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k)
+ case let data as Data:
+ mpForm.append(data, withName: k)
+ case let uuid as UUID:
+ mpForm.append(uuid.uuidString.data(using: String.Encoding.utf8)!, withName: k)
+ default:
+ fatalError("Unprocessable value \(v) with key \(k)")
+ }
+ }
+ }
+ }, to: URLString, method: xMethod, headers: nil)
+ .uploadProgress { progress in
+ if let onProgressReady = self.onProgressReady {
+ onProgressReady(progress)
+ }
+ }
+
+ requestTask.set(request: upload)
+
+ self.processRequest(request: upload, managerId, apiResponseQueue, completion)
+ } else if contentType.hasPrefix("application/x-www-form-urlencoded") {
+ encoding = URLEncoding(destination: .httpBody)
+ } else {
+ fatalError("Unsupported Media Type - \(contentType)")
+ }
+
+ default:
+ fatalError("Unsupported HTTPMethod - \(xMethod.rawValue)")
+ }
+
+ if let encoding = encoding {
+ let request = makeRequest(manager: manager, method: xMethod, encoding: encoding, headers: headers)
+ if let onProgressReady = self.onProgressReady {
+ onProgressReady(request.uploadProgress)
+ }
+ processRequest(request: request, managerId, apiResponseQueue, completion)
+ requestTask.set(request: request)
+ }
+
+ return requestTask
+ }
+
+ fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) {
+ if let credential = self.credential {
+ request.authenticate(with: credential)
+ }
+
+ let cleanupRequest = {
+ AlamofireRequestBuilderConfiguration.shared.managerStore[managerId] = nil
+ }
+
+ let validatedRequest = request.validate(statusCode: {{projectName}}API.shared.successfulStatusCodeRange)
+
+ switch T.self {
+ case is Void.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: {{projectName}}API.shared.dataResponseSerializer,
+ completionHandler: { voidResponse in
+ cleanupRequest()
+
+ switch voidResponse.result {
+ case .success:
+ completion(.success(Response(response: voidResponse.response!, body: () as! T, bodyData: voidResponse.data)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error)))
+ }
+
+ })
+ default:
+ fatalError("Unsupported Response Body Type - \(String(describing: T.self))")
+ }
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func buildHeaders() -> [String: String] {
+ var httpHeaders = Alamofire.HTTPHeaders.default.dictionary
+ for (key, value) in headers {
+ httpHeaders[key] = value
+ }
+ return httpHeaders
+ }
+
+ fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? {
+
+ guard let contentDisposition = contentDisposition else {
+ return nil
+ }
+
+ let items = contentDisposition.components(separatedBy: ";")
+
+ var filename: String?
+
+ for contentItem in items {
+
+ let filenameKey = "filename="
+ guard let range = contentItem.range(of: filenameKey) else {
+ continue
+ }
+
+ filename = contentItem
+ return filename?
+ .replacingCharacters(in: range, with: "")
+ .replacingOccurrences(of: "\"", with: "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ return filename
+
+ }
+
+ fileprivate func getPath(from url: URL) throws -> String {
+
+ guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else {
+ throw DownloadException.requestMissingPath
+ }
+
+ if path.hasPrefix("/") {
+ path.remove(at: path.startIndex)
+ }
+
+ return path
+
+ }
+
+ fileprivate func getURL(from urlRequest: URLRequest) throws -> URL {
+
+ guard let url = urlRequest.url else {
+ throw DownloadException.requestMissingURL
+ }
+
+ return url
+ }
+
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder, @unchecked Sendable {
+
+ override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) {
+ if let credential = self.credential {
+ request.authenticate(with: credential)
+ }
+
+ let cleanupRequest = {
+ AlamofireRequestBuilderConfiguration.shared.managerStore[managerId] = nil
+ }
+
+ let validatedRequest = request.validate(statusCode: {{projectName}}API.shared.successfulStatusCodeRange)
+
+ switch T.self {
+ case is String.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: {{projectName}}API.shared.stringResponseSerializer,
+ completionHandler: { stringResponse in
+ cleanupRequest()
+
+ switch stringResponse.result {
+ case let .success(value):
+ completion(.success(Response(response: stringResponse.response!, body: value as! T, bodyData: stringResponse.data)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error)))
+ }
+
+ })
+ case is URL.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: {{projectName}}API.shared.dataResponseSerializer,
+ completionHandler: { dataResponse in
+ cleanupRequest()
+
+ do {
+
+ guard case .success = dataResponse.result else {
+ throw DownloadException.responseFailed
+ }
+
+ guard let data = dataResponse.data else {
+ throw DownloadException.responseDataMissing
+ }
+
+ guard let request = request.request else {
+ throw DownloadException.requestMissing
+ }
+
+ let fileManager = FileManager.default
+ let urlRequest = try request.asURLRequest()
+ let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
+ let requestURL = try self.getURL(from: urlRequest)
+
+ var requestPath = try self.getPath(from: requestURL)
+
+ if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) {
+ requestPath = requestPath.appending("/\(headerFileName)")
+ } else {
+ requestPath = requestPath.appending("/tmp.{{projectName}}.\(UUID().uuidString)")
+ }
+
+ let filePath = cachesDirectory.appendingPathComponent(requestPath)
+ let directoryPath = filePath.deletingLastPathComponent().path
+
+ try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil)
+ try data.write(to: filePath, options: .atomic)
+
+ completion(.success(Response(response: dataResponse.response!, body: filePath as! T, bodyData: data)))
+
+ } catch let requestParserError as DownloadException {
+ completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError)))
+ } catch {
+ completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, error)))
+ }
+ return
+ })
+ case is Void.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: {{projectName}}API.shared.dataResponseSerializer,
+ completionHandler: { voidResponse in
+ cleanupRequest()
+
+ switch voidResponse.result {
+ case .success:
+ completion(.success(Response(response: voidResponse.response!, body: () as! T, bodyData: voidResponse.data)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error)))
+ }
+
+ })
+ case is Data.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: {{projectName}}API.shared.dataResponseSerializer,
+ completionHandler: { dataResponse in
+ cleanupRequest()
+
+ switch dataResponse.result {
+ case .success:
+ completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as! T, bodyData: dataResponse.data)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error)))
+ }
+
+ })
+ default:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: {{projectName}}API.shared.dataResponseSerializer,
+ completionHandler: { dataResponse in
+ cleanupRequest()
+
+ if case let .failure(error) = dataResponse.result {
+ completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error)))
+ return
+ }
+
+ guard let httpResponse = dataResponse.response else {
+ completion(.failure(ErrorResponse.error(-2, nil, dataResponse.response, DecodableRequestBuilderError.nilHTTPResponse)))
+ return
+ }
+
+ guard let unwrappedData = dataResponse.data, !unwrappedData.isEmpty else {
+ if let expressibleByNilLiteralType = T.self as? ExpressibleByNilLiteral.Type {
+ completion(.success(Response(response: httpResponse, body: expressibleByNilLiteralType.init(nilLiteral: ()) as! T, bodyData: dataResponse.data)))
+ } else {
+ completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, httpResponse, DecodableRequestBuilderError.emptyDataResponse)))
+ }
+ return
+ }
+
+ let decodeResult = CodableHelper.shared.decode(T.self, from: unwrappedData)
+
+ switch decodeResult {
+ case let .success(decodableObj):
+ completion(.success(Response(response: httpResponse, body: decodableObj, bodyData: unwrappedData)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(httpResponse.statusCode, unwrappedData, httpResponse, error)))
+ }
+
+ })
+ }
+ }
+
+}
+
+extension JSONDataEncoding: ParameterEncoding {
+
+ // MARK: Encoding
+
+ /// Creates a URL request by encoding parameters and applying them onto an existing request.
+ ///
+ /// - parameter urlRequest: The request to have parameters applied.
+ /// - parameter parameters: The parameters to apply. This should have a single key/value
+ /// pair with "jsonData" as the key and a Data object as the value.
+ ///
+ /// - throws: An `Error` if the encoding process encounters an error.
+ ///
+ /// - returns: The encoded request.
+ public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
+ let urlRequest = try urlRequest.asURLRequest()
+
+ return encode(urlRequest, with: parameters)
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/libraries/urlsession/URLSessionImplementations.mustache b/modules/openapi-generator/src/main/resources/swift6/libraries/urlsession/URLSessionImplementations.mustache
new file mode 100644
index 000000000000..73aec0eeeedb
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/libraries/urlsession/URLSessionImplementations.mustache
@@ -0,0 +1,676 @@
+// URLSessionImplementations.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if !os(macOS)
+import MobileCoreServices
+#endif
+#if canImport(UniformTypeIdentifiers)
+import UniformTypeIdentifiers
+#endif
+
+// Protocol defined for a session data task. This allows mocking out the URLSessionProtocol below since
+// you may not want to create or return a real URLSessionDataTask.
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol URLSessionDataTaskProtocol {
+ func resume()
+
+ var taskIdentifier: Int { get }
+
+ var progress: Progress { get }
+
+ func cancel()
+}
+
+// Protocol allowing implementations to alter what is returned or to test their implementations.
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol URLSessionProtocol {
+ // Task which performs the network fetch. Expected to be from URLSession.dataTask(with:completionHandler:) such that a network request
+ // is sent off when `.resume()` is called.
+ func dataTaskFromProtocol(with request: URLRequest, completionHandler: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void) -> URLSessionDataTaskProtocol
+}
+
+extension URLSession: URLSessionProtocol {
+ // Passthrough to URLSession.dataTask(with:completionHandler) since URLSessionDataTask conforms to URLSessionDataTaskProtocol and fetches the network data.
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func dataTaskFromProtocol(with request: URLRequest, completionHandler: @escaping @Sendable (Data?, URLResponse?, (any Error)?) -> Void) -> URLSessionDataTaskProtocol {
+ return dataTask(with: request, completionHandler: completionHandler)
+ }
+}
+
+extension URLSessionDataTask: URLSessionDataTaskProtocol {}
+
+class URLSessionRequestBuilderFactory: RequestBuilderFactory {
+ func getNonDecodableBuilder() -> RequestBuilder.Type {
+ return URLSessionRequestBuilder.self
+ }
+
+ func getBuilder() -> RequestBuilder.Type {
+ return URLSessionDecodableRequestBuilder.self
+ }
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{projectName}}APIChallengeHandler = ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))
+
+fileprivate class URLSessionRequestBuilderConfiguration: @unchecked Sendable {
+ private init() {
+ defaultURLSession = URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: nil)
+ }
+
+ static let shared = URLSessionRequestBuilderConfiguration()
+
+ // Store the URLSession's delegate to retain its reference
+ let sessionDelegate = SessionDelegate()
+
+ // Store the URLSession to retain its reference
+ let defaultURLSession: URLSession
+
+ // Store current taskDidReceiveChallenge for every URLSessionTask
+ var challengeHandlerStore = SynchronizedDictionary()
+
+ // Store current URLCredential for every URLSessionTask
+ var credentialStore = SynchronizedDictionary()
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class URLSessionRequestBuilder: RequestBuilder, @unchecked Sendable {
+
+ /**
+ May be assigned if you want to control the authentication challenges.
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var taskDidReceiveChallenge: {{projectName}}APIChallengeHandler?
+
+ required {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
+ super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication)
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the URLSession
+ configuration.
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createURLSession() -> URLSessionProtocol {
+ return URLSessionRequestBuilderConfiguration.shared.defaultURLSession
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the Content-Type
+ that is given to an uploaded form part.
+
+ Return nil to use the default behavior (inferring the Content-Type from
+ the file extension). Return the desired Content-Type otherwise.
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func contentTypeForFormPart(fileURL: URL) -> String? {
+ return nil
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the URLRequest
+ configuration (e.g. to override the cache policy).
+ */
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func createURLRequest(urlSession: URLSessionProtocol, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) throws -> URLRequest {
+
+ guard let url = URL(string: URLString) else {
+ throw DownloadException.requestMissingURL
+ }
+
+ var originalRequest = URLRequest(url: url)
+
+ originalRequest.httpMethod = method.rawValue
+
+ buildHeaders().forEach { key, value in
+ originalRequest.setValue(value, forHTTPHeaderField: key)
+ }
+
+ let modifiedRequest = try encoding.encode(originalRequest, with: parameters)
+
+ return modifiedRequest
+ }
+
+ @discardableResult
+ override {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func execute(_ apiResponseQueue: DispatchQueue = {{projectName}}API.shared.apiResponseQueue, _ completion: @Sendable @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> RequestTask {
+ let urlSession = createURLSession()
+
+ guard let xMethod = HTTPMethod(rawValue: method) else {
+ fatalError("Unsupported Http method - \(method)")
+ }
+
+ let encoding: ParameterEncoding
+
+ switch xMethod {
+ case .get, .head:
+ encoding = URLEncoding()
+
+ case .options, .post, .put, .patch, .delete, .trace, .connect:
+ let contentType = headers["Content-Type"] ?? "application/json"
+
+ if contentType.hasPrefix("application/") && contentType.contains("json") {
+ encoding = JSONDataEncoding()
+ } else if contentType.hasPrefix("multipart/form-data") {
+ encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:))
+ } else if contentType.hasPrefix("application/x-www-form-urlencoded") {
+ encoding = FormURLEncoding()
+ } else if contentType.hasPrefix("application/octet-stream"){
+ encoding = OctetStreamEncoding()
+ } else {
+ fatalError("Unsupported Media Type - \(contentType)")
+ }
+ }
+
+ do {
+ let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers)
+
+ let dataTask = urlSession.dataTaskFromProtocol(with: request) { data, response, error in
+ apiResponseQueue.async {
+ self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion)
+ self.cleanupRequest()
+ }
+ }
+
+ onProgressReady?(dataTask.progress)
+
+ URLSessionRequestBuilderConfiguration.shared.challengeHandlerStore[dataTask.taskIdentifier] = taskDidReceiveChallenge
+ URLSessionRequestBuilderConfiguration.shared.credentialStore[dataTask.taskIdentifier] = credential
+
+ requestTask.set(task: dataTask)
+
+ dataTask.resume()
+ } catch {
+ apiResponseQueue.async {
+ completion(.failure(ErrorResponse.error(415, nil, nil, error)))
+ }
+ }
+
+ return requestTask
+ }
+
+ private func cleanupRequest() {
+ if let task = requestTask.get() {
+ URLSessionRequestBuilderConfiguration.shared.challengeHandlerStore[task.taskIdentifier] = nil
+ URLSessionRequestBuilderConfiguration.shared.credentialStore[task.taskIdentifier] = nil
+ }
+ }
+
+ fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) {
+
+ if let error = error {
+ completion(.failure(ErrorResponse.error(-1, data, response, error)))
+ return
+ }
+
+ guard let httpResponse = response as? HTTPURLResponse else {
+ completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse)))
+ return
+ }
+
+ guard httpResponse.isStatusCodeSuccessful else {
+ completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode)))
+ return
+ }
+
+ switch T.self {
+ case is Void.Type:
+
+ completion(.success(Response(response: httpResponse, body: () as! T, bodyData: data)))
+
+ default:
+ fatalError("Unsupported Response Body Type - \(String(describing: T.self))")
+ }
+
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} func buildHeaders() -> [String: String] {
+ var httpHeaders: [String: String] = [:]
+ for (key, value) in {{projectName}}API.shared.customHeaders {
+ httpHeaders[key] = value
+ }
+ for (key, value) in headers {
+ httpHeaders[key] = value
+ }
+ return httpHeaders
+ }
+
+ fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? {
+
+ guard let contentDisposition = contentDisposition else {
+ return nil
+ }
+
+ let items = contentDisposition.components(separatedBy: ";")
+
+ var filename: String?
+
+ for contentItem in items {
+
+ let filenameKey = "filename="
+ guard let range = contentItem.range(of: filenameKey) else {
+ continue
+ }
+
+ filename = contentItem
+ return filename?
+ .replacingCharacters(in: range, with: "")
+ .replacingOccurrences(of: "\"", with: "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ return filename
+
+ }
+
+ fileprivate func getPath(from url: URL) throws -> String {
+
+ guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else {
+ throw DownloadException.requestMissingPath
+ }
+
+ if path.hasPrefix("/") {
+ path.remove(at: path.startIndex)
+ }
+
+ return path
+
+ }
+
+ fileprivate func getURL(from urlRequest: URLRequest) throws -> URL {
+
+ guard let url = urlRequest.url else {
+ throw DownloadException.requestMissingURL
+ }
+
+ return url
+ }
+
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class URLSessionDecodableRequestBuilder: URLSessionRequestBuilder, @unchecked Sendable {
+ override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) {
+
+ if let error = error {
+ completion(.failure(ErrorResponse.error(-1, data, response, error)))
+ return
+ }
+
+ guard let httpResponse = response as? HTTPURLResponse else {
+ completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse)))
+ return
+ }
+
+ guard httpResponse.isStatusCodeSuccessful else {
+ completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode)))
+ return
+ }
+
+ switch T.self {
+ case is String.Type:
+
+ let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
+
+ completion(.success(Response(response: httpResponse, body: body as! T, bodyData: data)))
+
+ case is URL.Type:
+ do {
+
+ guard error == nil else {
+ throw DownloadException.responseFailed
+ }
+
+ guard let data = data else {
+ throw DownloadException.responseDataMissing
+ }
+
+ let fileManager = FileManager.default
+ let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
+ let requestURL = try getURL(from: urlRequest)
+
+ var requestPath = try getPath(from: requestURL)
+
+ if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) {
+ requestPath = requestPath.appending("/\(headerFileName)")
+ } else {
+ requestPath = requestPath.appending("/tmp.{{projectName}}.\(UUID().uuidString)")
+ }
+
+ let filePath = cachesDirectory.appendingPathComponent(requestPath)
+ let directoryPath = filePath.deletingLastPathComponent().path
+
+ try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil)
+ try data.write(to: filePath, options: .atomic)
+
+ completion(.success(Response(response: httpResponse, body: filePath as! T, bodyData: data)))
+
+ } catch let requestParserError as DownloadException {
+ completion(.failure(ErrorResponse.error(400, data, response, requestParserError)))
+ } catch {
+ completion(.failure(ErrorResponse.error(400, data, response, error)))
+ }
+
+ case is Void.Type:
+
+ completion(.success(Response(response: httpResponse, body: () as! T, bodyData: data)))
+
+ case is Data.Type:
+
+ completion(.success(Response(response: httpResponse, body: data as! T, bodyData: data)))
+
+ default:
+
+ guard let unwrappedData = data, !unwrappedData.isEmpty else {
+ if let expressibleByNilLiteralType = T.self as? ExpressibleByNilLiteral.Type {
+ completion(.success(Response(response: httpResponse, body: expressibleByNilLiteralType.init(nilLiteral: ()) as! T, bodyData: data)))
+ } else {
+ completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse)))
+ }
+ return
+ }
+
+ let decodeResult = CodableHelper.shared.decode(T.self, from: unwrappedData)
+
+ switch decodeResult {
+ case let .success(decodableObj):
+ completion(.success(Response(response: httpResponse, body: decodableObj, bodyData: unwrappedData)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(httpResponse.statusCode, unwrappedData, response, error)))
+ }
+ }
+ }
+}
+
+fileprivate final class SessionDelegate: NSObject, URLSessionTaskDelegate {
+ func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
+
+ var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
+
+ var credential: URLCredential?
+
+ if let taskDidReceiveChallenge = URLSessionRequestBuilderConfiguration.shared.challengeHandlerStore[task.taskIdentifier] {
+ (disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
+ } else {
+ if challenge.previousFailureCount > 0 {
+ disposition = .rejectProtectionSpace
+ } else {
+ credential = URLSessionRequestBuilderConfiguration.shared.credentialStore[task.taskIdentifier] ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
+
+ if credential != nil {
+ disposition = .useCredential
+ }
+ }
+ }
+
+ completionHandler(disposition, credential)
+ }
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum HTTPMethod: String {
+ case options = "OPTIONS"
+ case get = "GET"
+ case head = "HEAD"
+ case post = "POST"
+ case put = "PUT"
+ case patch = "PATCH"
+ case delete = "DELETE"
+ case trace = "TRACE"
+ case connect = "CONNECT"
+}
+
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} protocol ParameterEncoding {
+ func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest
+}
+
+private class URLEncoding: ParameterEncoding {
+ func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest {
+
+ var urlRequest = urlRequest
+
+ guard let parameters = parameters else { return urlRequest }
+
+ guard let url = urlRequest.url else {
+ throw DownloadException.requestMissingURL
+ }
+
+ if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
+ urlComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters)
+ urlRequest.url = urlComponents.url
+ }
+
+ return urlRequest
+ }
+}
+
+private class FormDataEncoding: ParameterEncoding {
+
+ let contentTypeForFormPart: (_ fileURL: URL) -> String?
+
+ init(contentTypeForFormPart: @escaping (_ fileURL: URL) -> String?) {
+ self.contentTypeForFormPart = contentTypeForFormPart
+ }
+
+ func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest {
+
+ var urlRequest = urlRequest
+
+ guard let parameters = parameters, !parameters.isEmpty else {
+ return urlRequest
+ }
+
+ let boundary = "Boundary-\(UUID().uuidString)"
+
+ urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
+
+ for (key, value) in parameters {
+ for value in (value as? Array ?? [value]) {
+ switch value {
+ case let fileURL as URL:
+
+ urlRequest = try configureFileUploadRequest(
+ urlRequest: urlRequest,
+ boundary: boundary,
+ name: key,
+ fileURL: fileURL
+ )
+
+ case let string as String:
+
+ if let data = string.data(using: .utf8) {
+ urlRequest = configureDataUploadRequest(
+ urlRequest: urlRequest,
+ boundary: boundary,
+ name: key,
+ data: data
+ )
+ }
+
+ case let number as NSNumber:
+
+ if let data = number.stringValue.data(using: .utf8) {
+ urlRequest = configureDataUploadRequest(
+ urlRequest: urlRequest,
+ boundary: boundary,
+ name: key,
+ data: data
+ )
+ }
+
+ case let data as Data:
+
+ urlRequest = configureDataUploadRequest(
+ urlRequest: urlRequest,
+ boundary: boundary,
+ name: key,
+ data: data
+ )
+
+ case let uuid as UUID:
+
+ if let data = uuid.uuidString.data(using: .utf8) {
+ urlRequest = configureDataUploadRequest(
+ urlRequest: urlRequest,
+ boundary: boundary,
+ name: key,
+ data: data
+ )
+ }
+
+ default:
+ fatalError("Unprocessable value \(value) with key \(key)")
+ }
+ }
+ }
+
+ var body = urlRequest.httpBody.orEmpty
+
+ body.append("\r\n--\(boundary)--\r\n")
+
+ urlRequest.httpBody = body
+
+ return urlRequest
+ }
+
+ private func configureFileUploadRequest(urlRequest: URLRequest, boundary: String, name: String, fileURL: URL) throws -> URLRequest {
+
+ var urlRequest = urlRequest
+
+ var body = urlRequest.httpBody.orEmpty
+
+ let fileData = try Data(contentsOf: fileURL)
+
+ let mimetype = contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL)
+
+ let fileName = fileURL.lastPathComponent
+
+ // If we already added something then we need an additional newline.
+ if body.count > 0 {
+ body.append("\r\n")
+ }
+
+ // Value boundary.
+ body.append("--\(boundary)\r\n")
+
+ // Value headers.
+ body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(fileName)\"\r\n")
+ body.append("Content-Type: \(mimetype)\r\n")
+
+ // Separate headers and body.
+ body.append("\r\n")
+
+ // The value data.
+ body.append(fileData)
+
+ urlRequest.httpBody = body
+
+ return urlRequest
+ }
+
+ private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest {
+
+ var urlRequest = urlRequest
+
+ var body = urlRequest.httpBody.orEmpty
+
+ // If we already added something then we need an additional newline.
+ if body.count > 0 {
+ body.append("\r\n")
+ }
+
+ // Value boundary.
+ body.append("--\(boundary)\r\n")
+
+ // Value headers.
+ body.append("Content-Disposition: form-data; name=\"\(name)\"\r\n")
+
+ // Separate headers and body.
+ body.append("\r\n")
+
+ // The value data.
+ body.append(data)
+
+ urlRequest.httpBody = body
+
+ return urlRequest
+
+ }
+
+ func mimeType(for url: URL) -> String {
+ let pathExtension = url.pathExtension
+
+ if #available(iOS 15, macOS 11, *) {
+ #if canImport(UniformTypeIdentifiers)
+ if let utType = UTType(filenameExtension: pathExtension) {
+ return utType.preferredMIMEType ?? "application/octet-stream"
+ }
+ #else
+ return "application/octet-stream"
+ #endif
+ } else {
+ if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue(),
+ let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
+ return mimetype as String
+ }
+ return "application/octet-stream"
+ }
+ return "application/octet-stream"
+ }
+
+}
+
+private class FormURLEncoding: ParameterEncoding {
+ func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest {
+
+ var urlRequest = urlRequest
+
+ var requestBodyComponents = URLComponents()
+ requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:])
+
+ if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
+ urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
+ }
+
+ urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8)
+
+ return urlRequest
+ }
+}
+
+private class OctetStreamEncoding: ParameterEncoding {
+ func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest {
+
+ var urlRequest = urlRequest
+
+ guard let body = parameters?["body"] else { return urlRequest }
+
+ if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
+ urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
+ }
+
+ switch body {
+ case let fileURL as URL:
+ urlRequest.httpBody = try Data(contentsOf: fileURL)
+ case let data as Data:
+ urlRequest.httpBody = data
+ default:
+ fatalError("Unprocessable body \(body)")
+ }
+
+ return urlRequest
+ }
+}
+
+private extension Data {
+ /// Append string to Data
+ ///
+ /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8.
+ ///
+ /// - parameter string: The string to be added to the `Data`.
+
+ mutating func append(_ string: String) {
+ if let data = string.data(using: .utf8) {
+ append(data)
+ }
+ }
+}
+
+private extension Optional where Wrapped == Data {
+ var orEmpty: Data {
+ self ?? Data()
+ }
+}
+
+extension JSONDataEncoding: ParameterEncoding {}
diff --git a/modules/openapi-generator/src/main/resources/swift6/model.mustache b/modules/openapi-generator/src/main/resources/swift6/model.mustache
new file mode 100644
index 000000000000..b6a725d05262
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/model.mustache
@@ -0,0 +1,30 @@
+{{#models}}{{#model}}//
+// {{classname}}.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif{{#useVapor}}
+import Vapor{{/useVapor}}
+{{#swiftUseApiNamespace}}
+
+@available(*, deprecated, renamed: "{{projectName}}API.{{classname}}")
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{classname}} = {{projectName}}API.{{classname}}
+
+extension {{projectName}}API {
+{{/swiftUseApiNamespace}}
+{{#description}}
+
+/** {{.}} */{{/description}}{{#isDeprecated}}
+@available(*, deprecated, message: "This schema is deprecated."){{/isDeprecated}}{{#vendorExtensions.x-is-one-of-interface}}
+{{> modelOneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#isArray}}
+{{> modelArray}}{{/isArray}}{{^isArray}}{{#isEnum}}
+{{> modelEnum}}{{/isEnum}}{{^isEnum}}
+{{> modelObject}}{{/isEnum}}{{/isArray}}{{/vendorExtensions.x-is-one-of-interface}}{{/model}}{{/models}}
+{{#swiftUseApiNamespace}}
+}
+{{/swiftUseApiNamespace}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/swift6/modelArray.mustache b/modules/openapi-generator/src/main/resources/swift6/modelArray.mustache
new file mode 100644
index 000000000000..536c5e9eea49
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/modelArray.mustache
@@ -0,0 +1 @@
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} typealias {{classname}} = {{parent}}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/swift6/modelEnum.mustache b/modules/openapi-generator/src/main/resources/swift6/modelEnum.mustache
new file mode 100644
index 000000000000..060a14ce74c7
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/modelEnum.mustache
@@ -0,0 +1,7 @@
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{^isString}}{{^isInteger}}{{^isFloat}}{{^isDouble}}, JSONEncodable{{/isDouble}}{{/isFloat}}{{/isInteger}}{{/isString}}{{/useVapor}}, CaseIterable{{#enumUnknownDefaultCase}}{{#isInteger}}, CaseIterableDefaultsLast{{/isInteger}}{{#isFloat}}, CaseIterableDefaultsLast{{/isFloat}}{{#isDouble}}, CaseIterableDefaultsLast{{/isDouble}}{{#isString}}, CaseIterableDefaultsLast{{/isString}}{{/enumUnknownDefaultCase}} {
+{{#allowableValues}}
+{{#enumVars}}
+ case {{{name}}} = {{{value}}}
+{{/enumVars}}
+{{/allowableValues}}
+}
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/swift6/modelInlineEnumDeclaration.mustache b/modules/openapi-generator/src/main/resources/swift6/modelInlineEnumDeclaration.mustache
new file mode 100644
index 000000000000..27f1e51a979b
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/modelInlineEnumDeclaration.mustache
@@ -0,0 +1,7 @@
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{^isContainer}}{{^isString}}{{^isInteger}}{{^isFloat}}{{^isDouble}}, JSONEncodable{{/isDouble}}{{/isFloat}}{{/isInteger}}{{/isString}}{{/isContainer}}{{/useVapor}}, CaseIterable{{#enumUnknownDefaultCase}}{{#isInteger}}, CaseIterableDefaultsLast{{/isInteger}}{{#isFloat}}, CaseIterableDefaultsLast{{/isFloat}}{{#isDouble}}, CaseIterableDefaultsLast{{/isDouble}}{{#isString}}, CaseIterableDefaultsLast{{/isString}}{{#isContainer}}, CaseIterableDefaultsLast{{/isContainer}}{{/enumUnknownDefaultCase}} {
+ {{#allowableValues}}
+ {{#enumVars}}
+ case {{{name}}} = {{{value}}}
+ {{/enumVars}}
+ {{/allowableValues}}
+ }
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/resources/swift6/modelObject.mustache b/modules/openapi-generator/src/main/resources/swift6/modelObject.mustache
new file mode 100644
index 000000000000..71025d946997
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/modelObject.mustache
@@ -0,0 +1,137 @@
+{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#useClasses}}final class{{/useClasses}}{{^useClasses}}struct{{/useClasses}} {{{classname}}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{#useJsonEncodable}}, JSONEncodable{{/useJsonEncodable}}{{/useVapor}}{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}} {
+{{/objcCompatible}}{{#objcCompatible}}@objcMembers {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable{{#useJsonEncodable}}, JSONEncodable{{/useJsonEncodable}} {
+{{/objcCompatible}}
+
+{{#allVars}}
+{{#isEnum}}
+{{> modelInlineEnumDeclaration}}
+{{/isEnum}}
+{{/allVars}}
+{{#allVars}}
+{{#validatable}}
+{{#hasValidation}}
+{{#isString}}
+ static let {{{name}}}Rule = StringRule(minLength: {{#minLength}}{{{.}}}{{/minLength}}{{^minLength}}nil{{/minLength}}, maxLength: {{#maxLength}}{{{.}}}{{/maxLength}}{{^maxLength}}nil{{/maxLength}}, pattern: {{#pattern}}"{{{.}}}"{{/pattern}}{{^pattern}}nil{{/pattern}})
+{{/isString}}
+{{#isNumeric}}
+ static let {{{name}}}Rule = NumericRule<{{{dataType}}}>(minimum: {{#minimum}}{{{.}}}{{/minimum}}{{^minimum}}nil{{/minimum}}, exclusiveMinimum: {{#exclusiveMinimum}}true{{/exclusiveMinimum}}{{^exclusiveMinimum}}false{{/exclusiveMinimum}}, maximum: {{#maximum}}{{{.}}}{{/maximum}}{{^maximum}}nil{{/maximum}}, exclusiveMaximum: {{#exclusiveMaximum}}true{{/exclusiveMaximum}}{{^exclusiveMaximum}}false{{/exclusiveMaximum}}, multipleOf: {{#multipleOf}}{{{.}}}{{/multipleOf}}{{^multipleOf}}nil{{/multipleOf}})
+{{/isNumeric}}
+{{#isArray}}
+ static let {{{name}}}Rule = ArrayRule(minItems: {{#minItems}}{{{.}}}{{/minItems}}{{^minItems}}nil{{/minItems}}, maxItems: {{#maxItems}}{{{.}}}{{/maxItems}}{{^maxItems}}nil{{/maxItems}}, uniqueItems: {{#uniqueItems}}true{{/uniqueItems}}{{^uniqueItems}}false{{/uniqueItems}})
+{{/isArray}}
+{{/hasValidation}}
+{{/validatable}}
+{{/allVars}}
+{{#allVars}}
+{{#isEnum}}
+ {{#description}}/** {{{.}}} */
+ {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.")
+ {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{{name}}}: {{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatypeWithEnum}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}{{#defaultValue}} = {{#vendorExtensions.x-null-encodable}}{{{vendorExtensions.x-null-encodable-default-value}}}{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}{{/defaultValue}}
+{{/isEnum}}
+{{^isEnum}}
+ {{#description}}/** {{{.}}} */
+ {{/description}}{{#deprecated}}@available(*, deprecated, message: "This property is deprecated.")
+ {{/deprecated}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var {{{name}}}: {{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatype}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatype}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}{{#defaultValue}} = {{#vendorExtensions.x-null-encodable}}{{{vendorExtensions.x-null-encodable-default-value}}}{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}{{/defaultValue}}
+ {{#objcCompatible}}
+ {{#vendorExtensions.x-swift-optional-scalar}}
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{{name}}}Num: NSNumber? {
+ get {
+ {{^vendorExtensions.x-null-encodable}}
+ return {{{name}}} as NSNumber?
+ {{/vendorExtensions.x-null-encodable}}
+ {{#vendorExtensions.x-null-encodable}}
+ if case .encodeValue(let value) = {{name}} {
+ return value as NSNumber?
+ } else {
+ return nil
+ }
+ {{/vendorExtensions.x-null-encodable}}
+ }
+ }
+ {{/vendorExtensions.x-swift-optional-scalar}}
+ {{/objcCompatible}}
+{{/isEnum}}
+{{/allVars}}
+{{#hasVars}}
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init({{#allVars}}{{{name}}}: {{#vendorExtensions.x-null-encodable}}NullEncodable<{{{datatypeWithEnum}}}>{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{datatypeWithEnum}}}{{#required}}{{#isNullable}}?{{/isNullable}}{{/required}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}{{#defaultValue}} = {{#vendorExtensions.x-null-encodable}}{{{vendorExtensions.x-null-encodable-default-value}}}{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}{{/defaultValue}}{{^defaultValue}}{{^required}} = {{#vendorExtensions.x-null-encodable}}.encodeNull{{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}nil{{/vendorExtensions.x-null-encodable}}{{/required}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allVars}}) {
+ {{#allVars}}
+ self.{{{name}}} = {{{name}}}
+ {{/allVars}}
+ }
+{{/hasVars}}
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum CodingKeys: {{#hasVars}}String, {{/hasVars}}CodingKey, CaseIterable {
+ {{#allVars}}
+ case {{{name}}}{{#vendorExtensions.x-codegen-escaped-property-name}} = "{{{baseName}}}"{{/vendorExtensions.x-codegen-escaped-property-name}}
+ {{/allVars}}
+ }{{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} {{#readonlyProperties}}private(set) {{/readonlyProperties}}var additionalProperties: [String: {{{additionalPropertiesType}}}] = [:]
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} subscript(key: String) -> {{{additionalPropertiesType}}}? {
+ get {
+ if let value = additionalProperties[key] {
+ return value
+ }
+ return nil
+ }
+
+ set {
+ additionalProperties[key] = newValue
+ }
+ }{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}}
+
+ // Encodable protocol methods
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ {{#allVars}}
+ {{#vendorExtensions.x-null-encodable}}
+ switch {{{name}}} {
+ case .encodeNothing: break
+ case .encodeNull, .encodeValue: try container.encode({{{name}}}, forKey: .{{{name}}})
+ }
+ {{/vendorExtensions.x-null-encodable}}
+ {{^vendorExtensions.x-null-encodable}}
+ try container.encode{{^required}}IfPresent{{/required}}({{{name}}}, forKey: .{{{name}}})
+ {{/vendorExtensions.x-null-encodable}}
+ {{/allVars}}
+ {{#generateModelAdditionalProperties}}
+ {{#additionalPropertiesType}}
+ var additionalPropertiesContainer = encoder.container(keyedBy: String.self)
+ try additionalPropertiesContainer.encodeMap(additionalProperties)
+ {{/additionalPropertiesType}}
+ {{/generateModelAdditionalProperties}}
+ }{{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}
+
+ // Decodable protocol methods
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}}{{#objcCompatible}} required{{/objcCompatible}} init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+
+ {{#allVars}}
+ {{{name}}} = try container.decode{{#required}}{{#isNullable}}IfPresent{{/isNullable}}{{/required}}{{^required}}IfPresent{{/required}}({{{datatypeWithEnum}}}.self, forKey: .{{{name}}})
+ {{/allVars}}
+ var nonAdditionalPropertyKeys = Set()
+ {{#allVars}}
+ nonAdditionalPropertyKeys.insert("{{{baseName}}}")
+ {{/allVars}}
+ let additionalPropertiesContainer = try decoder.container(keyedBy: String.self)
+ additionalProperties = try additionalPropertiesContainer.decodeMap({{{additionalPropertiesType}}}.self, excludedKeys: nonAdditionalPropertyKeys)
+ }{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}}{{^objcCompatible}}{{#useClasses}}{{#vendorExtensions.x-swift-hashable}}
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func == (lhs: {{classname}}, rhs: {{classname}}) -> Bool {
+ {{#allVars}}
+ lhs.{{{name}}} == rhs.{{{name}}}{{^-last}} &&{{/-last}}
+ {{/allVars}}
+ {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}{{#hasVars}}&& {{/hasVars}}lhs.additionalProperties == rhs.additionalProperties{{/additionalPropertiesType}}{{/generateModelAdditionalProperties}}
+ }
+
+ {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} func hash(into hasher: inout Hasher) {
+ {{#allVars}}
+ hasher.combine({{{name}}}{{^vendorExtensions.x-null-encodable}}{{^required}}?{{/required}}{{/vendorExtensions.x-null-encodable}}.hashValue)
+ {{/allVars}}
+ {{#generateModelAdditionalProperties}}{{#additionalPropertiesType}}hasher.combine(additionalProperties.hashValue){{/additionalPropertiesType}}{{/generateModelAdditionalProperties}}
+ }{{/vendorExtensions.x-swift-hashable}}{{/useClasses}}{{/objcCompatible}}
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/swift6/modelOneOf.mustache
new file mode 100644
index 000000000000..629de6611bfb
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/modelOneOf.mustache
@@ -0,0 +1,31 @@
+{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable, JSONEncodable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}}{{/useVapor}} {
+ {{#oneOf}}
+ case type{{.}}({{.}})
+ {{/oneOf}}
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ {{#oneOf}}
+ case .type{{.}}(let value):
+ try container.encode(value)
+ {{/oneOf}}
+ }
+ }
+
+ public init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ {{#oneOf}}
+ {{#-first}}
+ if let value = try? container.decode({{.}}.self) {
+ {{/-first}}
+ {{^-first}}
+ } else if let value = try? container.decode({{.}}.self) {
+ {{/-first}}
+ self = .type{{.}}(value)
+ {{/oneOf}}
+ } else {
+ throw DecodingError.typeMismatch(Self.Type.self, .init(codingPath: decoder.codingPath, debugDescription: "Unable to decode instance of {{classname}}"))
+ }
+ }
+}
diff --git a/modules/openapi-generator/src/main/resources/swift6/model_doc.mustache b/modules/openapi-generator/src/main/resources/swift6/model_doc.mustache
new file mode 100644
index 000000000000..952fc7deb006
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/model_doc.mustache
@@ -0,0 +1,11 @@
+{{#models}}{{#model}}# {{classname}}
+
+## Properties
+Name | Type | Description | Notes
+------------ | ------------- | ------------- | -------------
+{{#vars}}**{{{name}}}** | {{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isContainer}}[**{{dataType}}**]({{complexType}}.md){{/isContainer}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{#vendorExtensions.x-null-encodable}}.encodeValue({{{.}}}){{/vendorExtensions.x-null-encodable}}{{^vendorExtensions.x-null-encodable}}{{{.}}}{{/vendorExtensions.x-null-encodable}}]{{/defaultValue}}
+{{/vars}}
+
+[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
+
+{{/model}}{{/models}}
diff --git a/modules/openapi-generator/src/main/resources/swift6/swiftformat.mustache b/modules/openapi-generator/src/main/resources/swift6/swiftformat.mustache
new file mode 100644
index 000000000000..930072528014
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/swift6/swiftformat.mustache
@@ -0,0 +1,45 @@
+# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/
+#
+# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md
+#
+# file options
+
+# uncomment below to exclude files, folders
+#--exclude path/to/test1.swift,Snapshots,Build
+
+# format options
+
+--allman false
+--binarygrouping 4,8
+--commas always
+--comments indent
+--decimalgrouping 3,6
+--elseposition same-line
+--empty void
+--exponentcase lowercase
+--exponentgrouping disabled
+--fractiongrouping disabled
+--header ignore
+--hexgrouping 4,8
+--hexliteralcase uppercase
+--ifdef indent
+--indent 4
+--indentcase false
+--importgrouping testable-bottom
+--linebreaks lf
+--maxwidth none
+--octalgrouping 4,8
+--operatorfunc spaced
+--patternlet hoist
+--ranges spaced
+--self remove
+--semicolons inline
+--stripunusedargs always
+--swiftversion 5.4
+--trimwhitespace always
+--wraparguments preserve
+--wrapcollections preserve
+
+# rules
+
+--enable isEmpty
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift6ClientCodegenOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift6ClientCodegenOptionsProvider.java
new file mode 100644
index 000000000000..35076e5d7f61
--- /dev/null
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift6ClientCodegenOptionsProvider.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
+ * Copyright 2018 SmartBear Software
+ *
+ * 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
+ *
+ * https://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.
+ */
+
+package org.openapitools.codegen.options;
+
+import org.openapitools.codegen.CodegenConstants;
+import org.openapitools.codegen.languages.Swift6ClientCodegen;
+
+import com.google.common.collect.ImmutableMap;
+
+import java.util.Map;
+
+public class Swift6ClientCodegenOptionsProvider implements OptionsProvider {
+ public static final String SORT_PARAMS_VALUE = "false";
+ public static final String SORT_MODEL_PROPERTIES_VALUE = "false";
+ public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true";
+ public static final String PROJECT_NAME_VALUE = "Swagger";
+ public static final String RESPONSE_AS_VALUE = "test";
+ public static final String NON_PUBLIC_API_REQUIRED_VALUE = "false";
+ public static final String OBJC_COMPATIBLE_VALUE = "false";
+ public static final String LENIENT_TYPE_CAST_VALUE = "false";
+ public static final String POD_SOURCE_VALUE = "{ :git => 'git@github.com:swagger-api/swagger-mustache.git'," +
+ " :tag => 'v1.0.0-SNAPSHOT' }";
+ public static final String POD_VERSION_VALUE = "v1.0.0-SNAPSHOT";
+ public static final String POD_AUTHORS_VALUE = "podAuthors";
+ public static final String POD_SOCIAL_MEDIA_URL_VALUE = "podSocialMediaURL";
+ public static final String POD_LICENSE_VALUE = "'Apache License, Version 2.0'";
+ public static final String POD_HOMEPAGE_VALUE = "podHomepage";
+ public static final String POD_SUMMARY_VALUE = "podSummary";
+ public static final String POD_DESCRIPTION_VALUE = "podDescription";
+ public static final String POD_SCREENSHOTS_VALUE = "podScreenshots";
+ public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL";
+ public static final String READONLY_PROPERTIES_VALUE = "false";
+ public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace";
+ public static final String USE_BACKTICKS_ESCAPES_VALUE = "false";
+ public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE = "true";
+ public static final String HASHABLE_MODELS_VALUE = "true";
+ public static final String USE_JSON_ENCODABLE_VALUE = "true";
+ public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false";
+ public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true";
+ public static final String LIBRARY_VALUE = "alamofire";
+ public static final String USE_SPM_FILE_STRUCTURE_VALUE = "false";
+ public static final String SWIFT_PACKAGE_PATH_VALUE = "";
+ public static final String ENUM_UNKNOWN_DEFAULT_CASE_VALUE = "false";
+ public static final String API_STATIC_METHOD_VALUE = "true";
+ public static final String COMBINE_DEFERRED_VALUE = "true";
+
+ @Override
+ public String getLanguage() {
+ return "swift6";
+ }
+
+ @Override
+ public Map createOptions() {
+ ImmutableMap.Builder builder = new ImmutableMap.Builder();
+ return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE)
+ .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE)
+ .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE)
+ .put(Swift6ClientCodegen.PROJECT_NAME, PROJECT_NAME_VALUE)
+ .put(Swift6ClientCodegen.RESPONSE_AS, RESPONSE_AS_VALUE)
+ .put(CodegenConstants.NON_PUBLIC_API, NON_PUBLIC_API_REQUIRED_VALUE)
+ .put(Swift6ClientCodegen.OBJC_COMPATIBLE, OBJC_COMPATIBLE_VALUE)
+ .put(Swift6ClientCodegen.LENIENT_TYPE_CAST, LENIENT_TYPE_CAST_VALUE)
+ .put(Swift6ClientCodegen.POD_SOURCE, POD_SOURCE_VALUE)
+ .put(CodegenConstants.POD_VERSION, POD_VERSION_VALUE)
+ .put(Swift6ClientCodegen.POD_AUTHORS, POD_AUTHORS_VALUE)
+ .put(Swift6ClientCodegen.POD_SOCIAL_MEDIA_URL, POD_SOCIAL_MEDIA_URL_VALUE)
+ .put(Swift6ClientCodegen.POD_LICENSE, POD_LICENSE_VALUE)
+ .put(Swift6ClientCodegen.POD_HOMEPAGE, POD_HOMEPAGE_VALUE)
+ .put(Swift6ClientCodegen.POD_SUMMARY, POD_SUMMARY_VALUE)
+ .put(Swift6ClientCodegen.POD_DESCRIPTION, POD_DESCRIPTION_VALUE)
+ .put(Swift6ClientCodegen.POD_SCREENSHOTS, POD_SCREENSHOTS_VALUE)
+ .put(Swift6ClientCodegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE)
+ .put(Swift6ClientCodegen.READONLY_PROPERTIES, READONLY_PROPERTIES_VALUE)
+ .put(Swift6ClientCodegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE)
+ .put(Swift6ClientCodegen.USE_BACKTICK_ESCAPES, USE_BACKTICKS_ESCAPES_VALUE)
+ .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true")
+ .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE)
+ .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)
+ .put(CodegenConstants.API_NAME_PREFIX, "")
+ .put(CodegenConstants.LIBRARY, LIBRARY_VALUE)
+ .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true")
+ .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true")
+ .put(Swift6ClientCodegen.USE_SPM_FILE_STRUCTURE, USE_SPM_FILE_STRUCTURE_VALUE)
+ .put(Swift6ClientCodegen.SWIFT_PACKAGE_PATH, SWIFT_PACKAGE_PATH_VALUE)
+ .put(Swift6ClientCodegen.GENERATE_MODEL_ADDITIONAL_PROPERTIES,
+ GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE)
+ .put(Swift6ClientCodegen.HASHABLE_MODELS, HASHABLE_MODELS_VALUE)
+ .put(Swift6ClientCodegen.USE_JSON_ENCODABLE, USE_JSON_ENCODABLE_VALUE)
+ .put(Swift6ClientCodegen.MAP_FILE_BINARY_TO_DATA, "false")
+ .put(Swift6ClientCodegen.USE_CUSTOM_DATE_WITHOUT_TIME, "false")
+ .put(Swift6ClientCodegen.VALIDATABLE, "true")
+ .put(Swift6ClientCodegen.USE_CLASSES, "false")
+ .put(Swift6ClientCodegen.API_STATIC_METHOD,
+ API_STATIC_METHOD_VALUE)
+ .put(Swift6ClientCodegen.COMBINE_DEFERRED,
+ COMBINE_DEFERRED_VALUE)
+ .put(CodegenConstants.ENUM_UNKNOWN_DEFAULT_CASE, ENUM_UNKNOWN_DEFAULT_CASE_VALUE)
+ .build();
+ }
+
+ @Override
+ public boolean isServer() {
+ return false;
+ }
+}
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelEnumTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelEnumTest.java
new file mode 100644
index 000000000000..af44086d3e21
--- /dev/null
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelEnumTest.java
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
+ * Copyright 2018 SmartBear Software
+ *
+ * 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
+ *
+ * https://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.
+ */
+
+package org.openapitools.codegen.swift6;
+
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.media.IntegerSchema;
+import io.swagger.v3.oas.models.media.NumberSchema;
+import io.swagger.v3.oas.models.media.Schema;
+import io.swagger.v3.oas.models.media.StringSchema;
+import org.openapitools.codegen.CodegenModel;
+import org.openapitools.codegen.CodegenProperty;
+import org.openapitools.codegen.DefaultCodegen;
+import org.openapitools.codegen.TestUtils;
+import org.openapitools.codegen.languages.Swift6ClientCodegen;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import java.math.BigDecimal;
+import java.util.Arrays;
+
+@SuppressWarnings("static-method")
+public class Swift6ClientCodegenModelEnumTest {
+ @Test(description = "convert a java model with a string enum and a default value")
+ public void convertStringDefaultValueTest() {
+ final StringSchema enumSchema = new StringSchema();
+ enumSchema.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3"));
+ enumSchema.setDefault("VALUE2");
+ final Schema model = new Schema().type("object").addProperty("name", enumSchema);
+
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
+ codegen.setOpenAPI(openAPI);
+ final CodegenModel cm = codegen.fromModel("sample", model);
+
+ Assert.assertEquals(cm.vars.size(), 1);
+
+ final CodegenProperty enumVar = cm.vars.get(0);
+ Assert.assertEquals(enumVar.baseName, "name");
+ Assert.assertEquals(enumVar.dataType, "String");
+ Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
+ Assert.assertEquals(enumVar.name, "name");
+ Assert.assertEquals(enumVar.defaultValue, ".value2");
+ Assert.assertEquals(enumVar.baseType, "String");
+ Assert.assertTrue(enumVar.isEnum);
+ }
+
+ @Test(description = "convert a java model with a reserved word string enum and a default value")
+ public void convertReservedWordStringDefaultValueTest() {
+ final StringSchema enumSchema = new StringSchema();
+ enumSchema.setEnum(Arrays.asList("1st", "2nd", "3rd"));
+ enumSchema.setDefault("2nd");
+ final Schema model = new Schema().type("object").addProperty("name", enumSchema);
+
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
+ codegen.setOpenAPI(openAPI);
+ final CodegenModel cm = codegen.fromModel("sample", model);
+
+ Assert.assertEquals(cm.vars.size(), 1);
+
+ final CodegenProperty enumVar = cm.vars.get(0);
+ Assert.assertEquals(enumVar.baseName, "name");
+ Assert.assertEquals(enumVar.dataType, "String");
+ Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
+ Assert.assertEquals(enumVar.name, "name");
+ Assert.assertEquals(enumVar.defaultValue, "._2nd");
+ Assert.assertEquals(enumVar.baseType, "String");
+ Assert.assertTrue(enumVar.isEnum);
+ }
+
+ @Test(description = "convert a java model with an integer enum and a default value")
+ public void convertIntegerDefaultValueTest() {
+ final IntegerSchema enumSchema = new IntegerSchema();
+ enumSchema.setEnum(Arrays.asList(1, 2, 3));
+ enumSchema.setDefault(2);
+ final Schema model = new Schema().type("object").addProperty("name", enumSchema);
+
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
+ codegen.setOpenAPI(openAPI);
+ final CodegenModel cm = codegen.fromModel("sample", model);
+
+ Assert.assertEquals(cm.vars.size(), 1);
+
+ final CodegenProperty enumVar = cm.vars.get(0);
+ Assert.assertEquals(enumVar.baseName, "name");
+ Assert.assertEquals(enumVar.dataType, "Int");
+ Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
+ Assert.assertEquals(enumVar.name, "name");
+ Assert.assertEquals(enumVar.defaultValue, "._2");
+ Assert.assertEquals(enumVar.baseType, "Int");
+ Assert.assertTrue(enumVar.isEnum);
+ }
+
+ @Test(description = "convert a java model with a number enum and a default value")
+ public void convertNumberDefaultValueTest() {
+ final NumberSchema enumSchema = new NumberSchema();
+ enumSchema.setEnum(Arrays.asList(new BigDecimal(10), new BigDecimal(100), new BigDecimal(1000)));
+ enumSchema.setDefault(new BigDecimal((100)));
+ final Schema model = new Schema().type("object").addProperty("name", enumSchema);
+
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
+ codegen.setOpenAPI(openAPI);
+ final CodegenModel cm = codegen.fromModel("sample", model);
+
+ Assert.assertEquals(cm.vars.size(), 1);
+
+ final CodegenProperty enumVar = cm.vars.get(0);
+ Assert.assertEquals(enumVar.baseName, "name");
+ Assert.assertEquals(enumVar.dataType, "Double");
+ Assert.assertEquals(enumVar.datatypeWithEnum, "Name");
+ Assert.assertEquals(enumVar.name, "name");
+ Assert.assertEquals(enumVar.defaultValue, "._100");
+ Assert.assertEquals(enumVar.baseType, "Double");
+ Assert.assertTrue(enumVar.isEnum);
+ }
+}
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelTest.java
new file mode 100644
index 000000000000..9de8e91b8caa
--- /dev/null
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelTest.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
+ * Copyright 2018 SmartBear Software
+ *
+ * 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
+ *
+ * https://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.
+ */
+
+package org.openapitools.codegen.swift6;
+
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.media.*;
+import io.swagger.v3.parser.util.SchemaTypeUtil;
+import org.openapitools.codegen.CodegenModel;
+import org.openapitools.codegen.CodegenProperty;
+import org.openapitools.codegen.DefaultCodegen;
+import org.openapitools.codegen.TestUtils;
+import org.openapitools.codegen.languages.Swift6ClientCodegen;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+@SuppressWarnings("static-method")
+public class Swift6ClientCodegenModelTest {
+
+ @Test(description = "convert a simple java model", enabled = true)
+ public void simpleModelTest() {
+ final Schema schema = new Schema()
+ .description("a sample model")
+ .addProperty("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT))
+ .addProperty("name", new StringSchema())
+ .addProperty("createdAt", new DateTimeSchema())
+ .addProperty("binary", new BinarySchema())
+ .addProperty("byte", new ByteArraySchema())
+ .addProperty("uuid", new UUIDSchema())
+ .addProperty("dateOfBirth", new DateSchema())
+ .addRequiredItem("id")
+ .addRequiredItem("name")
+ .discriminator(new Discriminator().propertyName("test"));
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema);
+ codegen.setOpenAPI(openAPI);
+ final CodegenModel cm = codegen.fromModel("sample", schema);
+
+ Assert.assertEquals(cm.name, "sample");
+ Assert.assertEquals(cm.classname, "Sample");
+ Assert.assertEquals(cm.description, "a sample model");
+ Assert.assertEquals(cm.vars.size(), 7);
+ Assert.assertEquals(cm.getDiscriminatorName(), "test");
+
+ final CodegenProperty property1 = cm.vars.get(0);
+ Assert.assertEquals(property1.baseName, "id");
+ Assert.assertEquals(property1.dataType, "Int64");
+ Assert.assertEquals(property1.name, "id");
+ Assert.assertNull(property1.defaultValue);
+ Assert.assertEquals(property1.baseType, "Int64");
+ Assert.assertTrue(property1.required);
+ Assert.assertTrue(property1.isPrimitiveType);
+ Assert.assertFalse(property1.isContainer);
+
+ final CodegenProperty property2 = cm.vars.get(1);
+ Assert.assertEquals(property2.baseName, "name");
+ Assert.assertEquals(property2.dataType, "String");
+ Assert.assertEquals(property2.name, "name");
+ Assert.assertNull(property2.defaultValue);
+ Assert.assertEquals(property2.baseType, "String");
+ Assert.assertTrue(property2.required);
+ Assert.assertTrue(property2.isPrimitiveType);
+ Assert.assertFalse(property2.isContainer);
+
+ final CodegenProperty property3 = cm.vars.get(2);
+ Assert.assertEquals(property3.baseName, "createdAt");
+ Assert.assertEquals(property3.dataType, "Date");
+ Assert.assertEquals(property3.name, "createdAt");
+ Assert.assertNull(property3.defaultValue);
+ Assert.assertEquals(property3.baseType, "Date");
+ Assert.assertFalse(property3.required);
+ Assert.assertFalse(property3.isContainer);
+
+ final CodegenProperty property4 = cm.vars.get(3);
+ Assert.assertEquals(property4.baseName, "binary");
+ Assert.assertEquals(property4.dataType, "URL");
+ Assert.assertEquals(property4.name, "binary");
+ Assert.assertNull(property4.defaultValue);
+ Assert.assertEquals(property4.baseType, "URL");
+ Assert.assertFalse(property4.required);
+ Assert.assertFalse(property4.isContainer);
+
+ final CodegenProperty property5 = cm.vars.get(4);
+ Assert.assertEquals(property5.baseName, "byte");
+ Assert.assertEquals(property5.dataType, "Data");
+ Assert.assertEquals(property5.name, "byte");
+ Assert.assertNull(property5.defaultValue);
+ Assert.assertEquals(property5.baseType, "Data");
+ Assert.assertFalse(property5.required);
+ Assert.assertFalse(property5.isContainer);
+
+ final CodegenProperty property6 = cm.vars.get(5);
+ Assert.assertEquals(property6.baseName, "uuid");
+ Assert.assertEquals(property6.dataType, "UUID");
+ Assert.assertEquals(property6.name, "uuid");
+ Assert.assertNull(property6.defaultValue);
+ Assert.assertEquals(property6.baseType, "UUID");
+ Assert.assertFalse(property6.required);
+ Assert.assertFalse(property6.isContainer);
+
+ final CodegenProperty property7 = cm.vars.get(6);
+ Assert.assertEquals(property7.baseName, "dateOfBirth");
+ Assert.assertEquals(property7.dataType, "Date");
+ Assert.assertEquals(property7.name, "dateOfBirth");
+ Assert.assertNull(property7.defaultValue);
+ Assert.assertEquals(property7.baseType, "Date");
+ Assert.assertFalse(property7.required);
+ Assert.assertFalse(property7.isContainer);
+ }
+
+ @Test(description = "convert a simple java model", enabled = true)
+ public void useCustomDateTimeTest() {
+ final Schema schema = new Schema()
+ .description("a sample model")
+ .addProperty("id", new IntegerSchema().format(SchemaTypeUtil.INTEGER64_FORMAT))
+ .addProperty("name", new StringSchema())
+ .addProperty("createdAt", new DateTimeSchema())
+ .addProperty("binary", new BinarySchema())
+ .addProperty("byte", new ByteArraySchema())
+ .addProperty("uuid", new UUIDSchema())
+ .addProperty("dateOfBirth", new DateSchema())
+ .addRequiredItem("id")
+ .addRequiredItem("name")
+ .discriminator(new Discriminator().propertyName("test"));
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", schema);
+ codegen.setOpenAPI(openAPI);
+ codegen.additionalProperties().put(Swift6ClientCodegen.USE_CUSTOM_DATE_WITHOUT_TIME, true);
+ codegen.processOpts();
+
+ final CodegenModel cm = codegen.fromModel("sample", schema);
+ final CodegenProperty property7 = cm.vars.get(6);
+
+ final CodegenProperty property3 = cm.vars.get(2);
+ Assert.assertEquals(property3.baseName, "createdAt");
+ Assert.assertEquals(property3.dataType, "Date");
+ Assert.assertEquals(property3.name, "createdAt");
+ Assert.assertNull(property3.defaultValue);
+ Assert.assertEquals(property3.baseType, "Date");
+ Assert.assertFalse(property3.required);
+ Assert.assertFalse(property3.isContainer);
+
+ Assert.assertEquals(property7.baseName, "dateOfBirth");
+ Assert.assertEquals(property7.dataType, "OpenAPIDateWithoutTime");
+ Assert.assertEquals(property7.name, "dateOfBirth");
+ Assert.assertNull(property7.defaultValue);
+ Assert.assertEquals(property7.baseType, "OpenAPIDateWithoutTime");
+ Assert.assertFalse(property7.required);
+ Assert.assertFalse(property7.isContainer);
+ }
+
+}
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenOptionsTest.java
new file mode 100644
index 000000000000..676390038dae
--- /dev/null
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenOptionsTest.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
+ * Copyright 2018 SmartBear Software
+ *
+ * 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
+ *
+ * https://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.
+ */
+
+package org.openapitools.codegen.swift6;
+
+import org.openapitools.codegen.AbstractOptionsTest;
+import org.openapitools.codegen.CodegenConfig;
+import org.openapitools.codegen.languages.Swift6ClientCodegen;
+import org.openapitools.codegen.options.Swift6ClientCodegenOptionsProvider;
+
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+
+public class Swift6ClientCodegenOptionsTest extends AbstractOptionsTest {
+ private Swift6ClientCodegen clientCodegen = mock(Swift6ClientCodegen.class, mockSettings);
+
+ public Swift6ClientCodegenOptionsTest() {
+ super(new Swift6ClientCodegenOptionsProvider());
+ }
+
+ @Override
+ protected CodegenConfig getCodegenConfig() {
+ return clientCodegen;
+ }
+
+ @SuppressWarnings("unused")
+ @Override
+ protected void verifyOptions() {
+ verify(clientCodegen).setSortParamsByRequiredFlag(Boolean.valueOf(Swift6ClientCodegenOptionsProvider.SORT_PARAMS_VALUE));
+ verify(clientCodegen).setProjectName(Swift6ClientCodegenOptionsProvider.PROJECT_NAME_VALUE);
+ verify(clientCodegen).setResponseAs(Swift6ClientCodegenOptionsProvider.RESPONSE_AS_VALUE.split(","));
+ verify(clientCodegen)
+ .setNonPublicApi(Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.NON_PUBLIC_API_REQUIRED_VALUE));
+ verify(clientCodegen).setObjcCompatible(Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.OBJC_COMPATIBLE_VALUE));
+ verify(clientCodegen).setLenientTypeCast(Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.LENIENT_TYPE_CAST_VALUE));
+ verify(clientCodegen).setPrependFormOrBodyParameters(
+ Boolean.valueOf(Swift6ClientCodegenOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE));
+ verify(clientCodegen)
+ .setReadonlyProperties(Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.READONLY_PROPERTIES_VALUE));
+ verify(clientCodegen).setGenerateModelAdditionalProperties(
+ Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE));
+ verify(clientCodegen).setHashableModels(Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.HASHABLE_MODELS_VALUE));
+ verify(clientCodegen)
+ .setEnumUnknownDefaultCase(Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.ENUM_UNKNOWN_DEFAULT_CASE_VALUE));
+ verify(clientCodegen).setApiStaticMethod(Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.API_STATIC_METHOD_VALUE));
+ verify(clientCodegen).setCombineDeferred(Boolean.parseBoolean(Swift6ClientCodegenOptionsProvider.COMBINE_DEFERRED_VALUE));
+ }
+}
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenTest.java
new file mode 100644
index 000000000000..8dfe1efd67c6
--- /dev/null
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenTest.java
@@ -0,0 +1,322 @@
+/*
+ * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
+ * Copyright 2018 SmartBear Software
+ *
+ * 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
+ *
+ * https://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.
+ */
+
+package org.openapitools.codegen.swift6;
+
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.Operation;
+import org.openapitools.codegen.*;
+import org.openapitools.codegen.config.CodegenConfigurator;
+import org.openapitools.codegen.languages.Swift6ClientCodegen;
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+public class Swift6ClientCodegenTest {
+
+ Swift6ClientCodegen swiftCodegen = new Swift6ClientCodegen();
+
+ @Test(enabled = true)
+ public void testCapitalizedReservedWord() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("AS", null), "_as");
+ }
+
+ @Test(enabled = true)
+ public void testReservedWord() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("Public", null), "_public");
+ }
+
+ @Test(enabled = true)
+ public void shouldNotBreakNonReservedWord() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("Error", null), "error");
+ }
+
+ @Test(enabled = true)
+ public void shouldNotBreakCorrectName() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("EntryName", null), "entryName");
+ }
+
+ @Test(enabled = true)
+ public void testSingleWordAllCaps() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("VALUE", null), "value");
+ }
+
+ @Test(enabled = true)
+ public void testSingleWordLowercase() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("value", null), "value");
+ }
+
+ @Test(enabled = true)
+ public void testCapitalsWithUnderscore() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY_NAME", null), "entryName");
+ }
+
+ @Test(enabled = true)
+ public void testCapitalsWithDash() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY-NAME", null), "entryName");
+ }
+
+ @Test(enabled = true)
+ public void testCapitalsWithSpace() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("ENTRY NAME", null), "entryName");
+ }
+
+ @Test(enabled = true)
+ public void testLowercaseWithUnderscore() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("entry_name", null), "entryName");
+ }
+
+ @Test(enabled = true)
+ public void testStartingWithNumber() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("123EntryName", null), "_123entryName");
+ Assert.assertEquals(swiftCodegen.toEnumVarName("123Entry_name", null), "_123entryName");
+ Assert.assertEquals(swiftCodegen.toEnumVarName("123EntryName123", null), "_123entryName123");
+ }
+
+ @Test(enabled = true)
+ public void testSpecialCharacters() throws Exception {
+ Assert.assertEquals(swiftCodegen.toEnumVarName("1:1", null), "_1Colon1");
+ Assert.assertEquals(swiftCodegen.toEnumVarName("1:One", null), "_1ColonOne");
+ Assert.assertEquals(swiftCodegen.toEnumVarName("Apple&Swift", null), "appleAmpersandSwift");
+ Assert.assertEquals(swiftCodegen.toEnumVarName("$", null), "dollar");
+ Assert.assertEquals(swiftCodegen.toEnumVarName("+1", null), "plus1");
+ Assert.assertEquals(swiftCodegen.toEnumVarName(">=", null), "greaterThanOrEqualTo");
+ }
+
+ @Test(description = "returns Data when response format is binary", enabled = true)
+ public void binaryDataTest() {
+ // TODO update json file
+
+ final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/binaryDataTest.json");
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setOpenAPI(openAPI);
+ final String path = "/tests/binaryResponse";
+ final Operation p = openAPI.getPaths().get(path).getPost();
+ final CodegenOperation op = codegen.fromOperation(path, "post", p, null);
+
+ Assert.assertEquals(op.returnType, "URL");
+ Assert.assertEquals(op.bodyParam.dataType, "URL");
+ Assert.assertTrue(op.bodyParam.isBinary);
+ Assert.assertTrue(op.responses.get(0).isBinary);
+ }
+
+ @Test(description = "returns Date when response format is date per default", enabled = true)
+ public void dateDefaultTest() {
+ final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json");
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setOpenAPI(openAPI);
+ final String path = "/tests/dateResponse";
+ final Operation p = openAPI.getPaths().get(path).getPost();
+ final CodegenOperation op = codegen.fromOperation(path, "post", p, null);
+
+ Assert.assertEquals(op.returnType, "Date");
+ Assert.assertEquals(op.bodyParam.dataType, "Date");
+ }
+
+ @Test(description = "returns Date when response format is date and cli option is disabled", enabled = true)
+ public void dateDisabledCLITest() {
+ final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json");
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setOpenAPI(openAPI);
+ codegen.additionalProperties().put(Swift6ClientCodegen.USE_CUSTOM_DATE_WITHOUT_TIME, false);
+ codegen.processOpts();
+ final String path = "/tests/dateResponse";
+ final Operation p = openAPI.getPaths().get(path).getPost();
+ final CodegenOperation op = codegen.fromOperation(path, "post", p, null);
+
+ Assert.assertEquals(op.returnType, "Date");
+ Assert.assertEquals(op.bodyParam.dataType, "Date");
+ }
+
+ @Test(description = "returns OpenAPIDateWithoutTime when response format is date and cli option is enabled", enabled = true)
+ public void dateWithoutTimeTest() {
+ final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/datePropertyTest.json");
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setOpenAPI(openAPI);
+ codegen.additionalProperties().put(Swift6ClientCodegen.USE_CUSTOM_DATE_WITHOUT_TIME, true);
+ codegen.processOpts();
+
+ final String path = "/tests/dateResponse";
+ final Operation p = openAPI.getPaths().get(path).getPost();
+ final CodegenOperation op = codegen.fromOperation(path, "post", p, null);
+
+ Assert.assertEquals(op.returnType, "OpenAPIDateWithoutTime");
+ Assert.assertEquals(op.bodyParam.dataType, "OpenAPIDateWithoutTime");
+ }
+
+ @Test(description = "type from languageSpecificPrimitives should not be prefixed", enabled = true)
+ public void prefixExceptionTest() {
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setModelNamePrefix("API");
+
+ final String result = codegen.toModelName("AnyCodable");
+ Assert.assertEquals(result, "AnyCodable");
+ }
+
+ @Test(description = "type from languageSpecificPrimitives should not be suffixed", enabled = true)
+ public void suffixExceptionTest() {
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setModelNameSuffix("API");
+
+ final String result = codegen.toModelName("AnyCodable");
+ Assert.assertEquals(result, "AnyCodable");
+ }
+
+ @Test(description = "Other types should be prefixed", enabled = true)
+ public void prefixTest() {
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setModelNamePrefix("API");
+
+ final String result = codegen.toModelName("MyType");
+ Assert.assertEquals(result, "APIMyType");
+ }
+
+ @Test(description = "Other types should be suffixed", enabled = true)
+ public void suffixTest() {
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setModelNameSuffix("API");
+
+ final String result = codegen.toModelName("MyType");
+ Assert.assertEquals(result, "MyTypeAPI");
+ }
+
+ @Test(enabled = true)
+ public void testDefaultPodAuthors() throws Exception {
+ // Given
+
+ // When
+ swiftCodegen.processOpts();
+
+ // Then
+ final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift6ClientCodegen.POD_AUTHORS);
+ Assert.assertEquals(podAuthors, Swift6ClientCodegen.DEFAULT_POD_AUTHORS);
+ }
+
+ @Test(enabled = true)
+ public void testPodAuthors() throws Exception {
+ // Given
+ final String openAPIDevs = "OpenAPI Devs";
+ swiftCodegen.additionalProperties().put(Swift6ClientCodegen.POD_AUTHORS, openAPIDevs);
+
+ // When
+ swiftCodegen.processOpts();
+
+ // Then
+ final String podAuthors = (String) swiftCodegen.additionalProperties().get(Swift6ClientCodegen.POD_AUTHORS);
+ Assert.assertEquals(podAuthors, openAPIDevs);
+ }
+
+ @Test(description = "Bug example code generation", enabled = true)
+ public void crashSwift6ExampleCodeGenerationStackOverflowTest() throws IOException {
+ // final OpenAPI openAPI =
+ // TestUtils.parseFlattenSpec("src/test/resources/bugs/Swift6CodeGenerationStackOverflow#2966.yaml");
+ Path target = Files.createTempDirectory("test");
+ File output = target.toFile();
+ try {
+ final CodegenConfigurator configurator = new CodegenConfigurator()
+ .setGeneratorName("swift6")
+ .setValidateSpec(false)
+ .setInputSpec("src/test/resources/bugs/Swift6CodeGenerationStackOverflow#2966.yaml")
+ .setEnablePostProcessFile(true)
+ .setOutputDir(target.toAbsolutePath().toString());
+
+ final ClientOptInput clientOptInput = configurator.toClientOptInput();
+ DefaultGenerator generator = new DefaultGenerator(false);
+
+ generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.API_DOCS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.ENABLE_POST_PROCESS_FILE, "true");
+
+ List files = generator.opts(clientOptInput).generate();
+ Assert.assertTrue(files.size() > 0, "No files generated");
+ } finally {
+ output.deleteOnExit();
+ }
+ }
+
+ @Test(description = "Bug example code generation 2", enabled = true)
+ public void crashSwift6ExampleCodeGenerationStackOverflowBug_2Test() throws IOException {
+ // final OpenAPI openAPI =
+ // TestUtils.parseFlattenSpec("src/test/resources/bugs/Swift6CodeGenerationStackOverflow#2966.yaml");
+ Path target = Files.createTempDirectory("test");
+ File output = target.toFile();
+ try {
+ final CodegenConfigurator configurator = new CodegenConfigurator()
+ .setGeneratorName("swift6")
+ .setValidateSpec(false)
+ // .setInputSpec("http://localhost:8080/api/openapi.yaml")
+ .setInputSpec("src/test/resources/bugs/Swift6CodeGenerationBug2.yaml")
+ // .setInputSpec("http://localhost:8080/api/openapi.yaml")
+ .setEnablePostProcessFile(true)
+ .setOutputDir(target.toAbsolutePath().toString());
+
+ final ClientOptInput clientOptInput = configurator.toClientOptInput();
+ DefaultGenerator generator = new DefaultGenerator(false);
+
+ generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.API_DOCS, "true");
+ generator.setGeneratorPropertyDefault(CodegenConstants.ENABLE_POST_PROCESS_FILE, "true");
+
+ List files = generator.opts(clientOptInput).generate();
+ Assert.assertTrue(files.size() > 0, "No files generated");
+ } finally {
+ output.deleteOnExit();
+ }
+ }
+
+ @Test(description = "optional form parameters when using oneOf schema", enabled = true)
+ public void oneOfFormParameterTest() {
+ final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_15511.yaml");
+ final DefaultCodegen codegen = new Swift6ClientCodegen();
+ codegen.setOpenAPI(openAPI);
+ codegen.processOpts();
+ final String path = "/as/token.oauth2";
+ final Operation p = openAPI.getPaths().get(path).getPost();
+ final CodegenOperation op = codegen.fromOperation(path, "post", p, null);
+
+ Assert.assertEquals(op.formParams.size(), 6);
+
+ Assert.assertEquals(op.formParams.get(0).baseName, "client_id");
+ Assert.assertEquals(op.formParams.get(1).baseName, "grant_type");
+ Assert.assertEquals(op.formParams.get(2).baseName, "password");
+ Assert.assertEquals(op.formParams.get(3).baseName, "scope");
+ Assert.assertEquals(op.formParams.get(4).baseName, "username");
+ Assert.assertEquals(op.formParams.get(5).baseName, "refresh_token");
+
+ Assert.assertEquals(op.formParams.get(0).required, false);
+ Assert.assertEquals(op.formParams.get(1).required, false);
+ Assert.assertEquals(op.formParams.get(2).required, false);
+ Assert.assertEquals(op.formParams.get(3).required, false);
+ Assert.assertEquals(op.formParams.get(4).required, false);
+ Assert.assertEquals(op.formParams.get(5).required, false);
+
+ }
+
+}
diff --git a/modules/openapi-generator/src/test/resources/bugs/Swift6CodeGenerationBug2.yaml b/modules/openapi-generator/src/test/resources/bugs/Swift6CodeGenerationBug2.yaml
new file mode 100644
index 000000000000..de5d6bba3e25
--- /dev/null
+++ b/modules/openapi-generator/src/test/resources/bugs/Swift6CodeGenerationBug2.yaml
@@ -0,0 +1,101 @@
+openapi: 3.0.1
+info:
+ title: XXX
+ description: Das ist jetzt der erste OpenAPI 3.0 Endpoint
+ contact:
+ email: XXX.XXX@XXX.de
+ version: "1.0"
+paths:
+ /api/v1/petresource/pet:
+ post:
+ tags:
+ - v1/petresource
+ summary: Save a Pet.
+ description: Save a Pet.
+ operationId: savePet
+ requestBody:
+ content:
+ '*/*':
+ schema:
+ $ref: '#/components/schemas/Pet'
+ responses:
+ default:
+ description: PetResponse
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Pet'
+ /api/v1/petresource/petstore:
+ post:
+ tags:
+ - v1/petresource
+ summary: Save a Petstore.
+ description: Save a Petstore.
+ operationId: savePetStore
+ requestBody:
+ content:
+ '*/*':
+ schema:
+ $ref: '#/components/schemas/PetStore'
+ responses:
+ default:
+ description: PetStore
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PetStore'
+components:
+ schemas:
+ Cat:
+ required:
+ - type
+ type: object
+ description: Cat
+ allOf:
+ - $ref: '#/components/schemas/Pet'
+ - type: object
+ properties:
+ catFood:
+ type: string
+ Dog:
+ required:
+ - type
+ type: object
+ description: Dog
+ allOf:
+ - $ref: '#/components/schemas/Pet'
+ - type: object
+ properties:
+ dogFood:
+ type: string
+ Pet:
+ required:
+ - type
+ type: object
+ properties:
+ name:
+ type: string
+ description: Name
+ store:
+ $ref: '#/components/schemas/PetStore'
+ mother:
+ $ref: '#/components/schemas/Pet'
+ father:
+ $ref: '#/components/schemas/Pet'
+ type:
+ type: string
+ description: Type Diskriminator
+ description: Base Pet
+ discriminator:
+ propertyName: type
+ mapping:
+ Dog: '#/components/schemas/Dog'
+ Cat: '#/components/schemas/Cat'
+ PetStore:
+ type: object
+ properties:
+ pets:
+ type: array
+ items:
+ $ref: '#/components/schemas/Pet'
+ description: PetStore
diff --git a/modules/openapi-generator/src/test/resources/bugs/Swift6CodeGenerationStackOverflow#2966.yaml b/modules/openapi-generator/src/test/resources/bugs/Swift6CodeGenerationStackOverflow#2966.yaml
new file mode 100644
index 000000000000..edfc6bfc1dec
--- /dev/null
+++ b/modules/openapi-generator/src/test/resources/bugs/Swift6CodeGenerationStackOverflow#2966.yaml
@@ -0,0 +1,49 @@
+openapi: 3.0.0
+info:
+ description: This spec is mainly for testing Petstore server
+ version: 1.0.0
+ title: OpenAPI Petstore
+ license:
+ name: Apache-2.0
+ url: http://www.apache.org/licenses/LICENSE-2.0.html
+tags:
+ - name: pet
+ description: Everything about your Pets
+paths:
+ /pet:
+ post:
+ tags:
+ - pet
+ summary: Add a new pet to the store
+ description: ""
+ operationId: addPet
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/Pet"
+ description: Pet object that needs to be added to the store
+ required: true
+ responses:
+ "400":
+ description: Invalid input
+servers:
+ - url: http://petstore.swagger.io:80/v2
+components:
+ schemas:
+ Pet:
+ type: object
+ required:
+ - name
+ properties:
+ id:
+ type: integer
+ format: int64
+ x-is-unique: true
+ name:
+ type: string
+ example: doggie
+ pets:
+ type: array
+ items:
+ $ref: "#/components/schemas/Pet"
diff --git a/samples/client/petstore/swift6/.gitignore b/samples/client/petstore/swift6/.gitignore
new file mode 100644
index 000000000000..5e5d5cebcf47
--- /dev/null
+++ b/samples/client/petstore/swift6/.gitignore
@@ -0,0 +1,63 @@
+# Xcode
+#
+# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
+
+## Build generated
+build/
+DerivedData
+
+## Various settings
+*.pbxuser
+!default.pbxuser
+*.mode1v3
+!default.mode1v3
+*.mode2v3
+!default.mode2v3
+*.perspectivev3
+!default.perspectivev3
+xcuserdata
+
+## Other
+*.xccheckout
+*.moved-aside
+*.xcuserstate
+*.xcscmblueprint
+
+## Obj-C/Swift specific
+*.hmap
+*.ipa
+
+## Playgrounds
+timeline.xctimeline
+playground.xcworkspace
+
+# Swift Package Manager
+#
+# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
+# Packages/
+.build/
+
+# CocoaPods
+#
+# We recommend against adding the Pods directory to your .gitignore. However
+# you should judge for yourself, the pros and cons are mentioned at:
+# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
+#
+# Pods/
+
+# Carthage
+#
+# Add this line if you want to avoid checking in source code from Carthage dependencies.
+# Carthage/Checkouts
+
+Carthage/Build
+
+# fastlane
+#
+# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
+# screenshots whenever they are needed.
+# For more information about the recommended setup visit:
+# https://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md
+
+fastlane/report.xml
+fastlane/screenshots
diff --git a/samples/client/petstore/swift6/alamofireLibrary/.gitignore b/samples/client/petstore/swift6/alamofireLibrary/.gitignore
new file mode 100644
index 000000000000..316a84507fb4
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/.gitignore
@@ -0,0 +1,100 @@
+# Created by https://www.toptal.com/developers/gitignore/api/xcode,swift
+# Edit at https://www.toptal.com/developers/gitignore?templates=xcode,swift
+
+### Swift ###
+# Xcode
+#
+# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
+
+## User settings
+xcuserdata/
+
+## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
+*.xcscmblueprint
+*.xccheckout
+
+## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
+build/
+DerivedData/
+*.moved-aside
+*.pbxuser
+!default.pbxuser
+*.mode1v3
+!default.mode1v3
+*.mode2v3
+!default.mode2v3
+*.perspectivev3
+!default.perspectivev3
+
+## Obj-C/Swift specific
+*.hmap
+
+## App packaging
+*.ipa
+*.dSYM.zip
+*.dSYM
+
+## Playgrounds
+timeline.xctimeline
+playground.xcworkspace
+
+# Swift Package Manager
+# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
+# Packages/
+# Package.pins
+# Package.resolved
+# *.xcodeproj
+# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
+# hence it is not needed unless you have added a package configuration file to your project
+# .swiftpm
+
+.build/
+
+# CocoaPods
+# We recommend against adding the Pods directory to your .gitignore. However
+# you should judge for yourself, the pros and cons are mentioned at:
+# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
+# Pods/
+# Add this line if you want to avoid checking in source code from the Xcode workspace
+# *.xcworkspace
+
+# Carthage
+# Add this line if you want to avoid checking in source code from Carthage dependencies.
+# Carthage/Checkouts
+
+Carthage/Build/
+
+# Accio dependency management
+Dependencies/
+.accio/
+
+# fastlane
+# It is recommended to not store the screenshots in the git repo.
+# Instead, use fastlane to re-generate the screenshots whenever they are needed.
+# For more information about the recommended setup visit:
+# https://docs.fastlane.tools/best-practices/source-control/#source-control
+
+fastlane/report.xml
+fastlane/Preview.html
+fastlane/screenshots/**/*.png
+fastlane/test_output
+
+# Code Injection
+# After new code Injection tools there's a generated folder /iOSInjectionProject
+# https://github.com/johnno1962/injectionforxcode
+
+iOSInjectionProject/
+
+### Xcode ###
+
+## Xcode 8 and earlier
+
+### Xcode Patch ###
+*.xcodeproj/*
+!*.xcodeproj/project.pbxproj
+!*.xcodeproj/xcshareddata/
+!*.xcworkspace/contents.xcworkspacedata
+/*.gcno
+**/xcshareddata/WorkspaceSettings.xcsettings
+
+# End of https://www.toptal.com/developers/gitignore/api/xcode,swift
diff --git a/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator-ignore b/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator-ignore
new file mode 100644
index 000000000000..7484ee590a38
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator-ignore
@@ -0,0 +1,23 @@
+# OpenAPI Generator Ignore
+# Generated by openapi-generator https://github.com/openapitools/openapi-generator
+
+# Use this file to prevent files from being overwritten by the generator.
+# The patterns follow closely to .gitignore or .dockerignore.
+
+# As an example, the C# client generator defines ApiClient.cs.
+# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
+#ApiClient.cs
+
+# You can match any string of characters against a directory, file or extension with a single asterisk (*):
+#foo/*/qux
+# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
+
+# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
+#foo/**/qux
+# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
+
+# You can also negate patterns with an exclamation (!).
+# For example, you can ignore all files in a docs folder with the file extension .md:
+#docs/*.md
+# Then explicitly reverse the ignore rule for a single file:
+#!docs/README.md
diff --git a/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator/FILES b/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator/FILES
new file mode 100644
index 000000000000..62ef6051b90d
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator/FILES
@@ -0,0 +1,108 @@
+.gitignore
+.swiftformat
+Cartfile
+Package.swift
+PetstoreClient.podspec
+PetstoreClient/Classes/OpenAPIs/APIHelper.swift
+PetstoreClient/Classes/OpenAPIs/APIs.swift
+PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift
+PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift
+PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift
+PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift
+PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift
+PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift
+PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift
+PetstoreClient/Classes/OpenAPIs/CodableHelper.swift
+PetstoreClient/Classes/OpenAPIs/Extensions.swift
+PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift
+PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift
+PetstoreClient/Classes/OpenAPIs/Models.swift
+PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift
+PetstoreClient/Classes/OpenAPIs/Models/Animal.swift
+PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift
+PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift
+PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift
+PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift
+PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift
+PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift
+PetstoreClient/Classes/OpenAPIs/Models/Cat.swift
+PetstoreClient/Classes/OpenAPIs/Models/Category.swift
+PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift
+PetstoreClient/Classes/OpenAPIs/Models/Client.swift
+PetstoreClient/Classes/OpenAPIs/Models/Dog.swift
+PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift
+PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift
+PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift
+PetstoreClient/Classes/OpenAPIs/Models/File.swift
+PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift
+PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift
+PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift
+PetstoreClient/Classes/OpenAPIs/Models/List.swift
+PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift
+PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift
+PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift
+PetstoreClient/Classes/OpenAPIs/Models/Name.swift
+PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift
+PetstoreClient/Classes/OpenAPIs/Models/Order.swift
+PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift
+PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift
+PetstoreClient/Classes/OpenAPIs/Models/Pet.swift
+PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift
+PetstoreClient/Classes/OpenAPIs/Models/Return.swift
+PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift
+PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift
+PetstoreClient/Classes/OpenAPIs/Models/Tag.swift
+PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift
+PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift
+PetstoreClient/Classes/OpenAPIs/Models/User.swift
+PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift
+PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift
+PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift
+PetstoreClient/Classes/OpenAPIs/Validation.swift
+README.md
+docs/AdditionalPropertiesClass.md
+docs/Animal.md
+docs/AnimalFarm.md
+docs/AnotherFakeAPI.md
+docs/ApiResponse.md
+docs/ArrayOfArrayOfNumberOnly.md
+docs/ArrayOfNumberOnly.md
+docs/ArrayTest.md
+docs/Capitalization.md
+docs/Cat.md
+docs/Category.md
+docs/ClassModel.md
+docs/Client.md
+docs/Dog.md
+docs/EnumArrays.md
+docs/EnumClass.md
+docs/EnumTest.md
+docs/FakeAPI.md
+docs/FakeClassnameTags123API.md
+docs/File.md
+docs/FileSchemaTestClass.md
+docs/FormatTest.md
+docs/HasOnlyReadOnly.md
+docs/List.md
+docs/MapTest.md
+docs/MixedPropertiesAndAdditionalPropertiesClass.md
+docs/Model200Response.md
+docs/Name.md
+docs/NumberOnly.md
+docs/Order.md
+docs/OuterComposite.md
+docs/OuterEnum.md
+docs/Pet.md
+docs/PetAPI.md
+docs/ReadOnlyFirst.md
+docs/Return.md
+docs/SpecialModelName.md
+docs/StoreAPI.md
+docs/StringBooleanMap.md
+docs/Tag.md
+docs/TypeHolderDefault.md
+docs/TypeHolderExample.md
+docs/User.md
+docs/UserAPI.md
+git_push.sh
+project.yml
diff --git a/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator/VERSION
new file mode 100644
index 000000000000..17f2442ff3bc
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/.openapi-generator/VERSION
@@ -0,0 +1 @@
+7.9.0-SNAPSHOT
diff --git a/samples/client/petstore/swift6/alamofireLibrary/.swiftformat b/samples/client/petstore/swift6/alamofireLibrary/.swiftformat
new file mode 100644
index 000000000000..930072528014
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/.swiftformat
@@ -0,0 +1,45 @@
+# This file is auto-generated by OpenAPI Generator: https://openapi-generator.tech/
+#
+# For rules on SwiftFormat, please refer to https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md
+#
+# file options
+
+# uncomment below to exclude files, folders
+#--exclude path/to/test1.swift,Snapshots,Build
+
+# format options
+
+--allman false
+--binarygrouping 4,8
+--commas always
+--comments indent
+--decimalgrouping 3,6
+--elseposition same-line
+--empty void
+--exponentcase lowercase
+--exponentgrouping disabled
+--fractiongrouping disabled
+--header ignore
+--hexgrouping 4,8
+--hexliteralcase uppercase
+--ifdef indent
+--indent 4
+--indentcase false
+--importgrouping testable-bottom
+--linebreaks lf
+--maxwidth none
+--octalgrouping 4,8
+--operatorfunc spaced
+--patternlet hoist
+--ranges spaced
+--self remove
+--semicolons inline
+--stripunusedargs always
+--swiftversion 5.4
+--trimwhitespace always
+--wraparguments preserve
+--wrapcollections preserve
+
+# rules
+
+--enable isEmpty
diff --git a/samples/client/petstore/swift6/alamofireLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/swift6/alamofireLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
new file mode 100644
index 000000000000..919434a6254f
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
@@ -0,0 +1,7 @@
+
+
+
+
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/.swiftpm/xcode/xcshareddata/xcschemes/PetstoreClient.xcscheme b/samples/client/petstore/swift6/alamofireLibrary/.swiftpm/xcode/xcshareddata/xcschemes/PetstoreClient.xcscheme
new file mode 100644
index 000000000000..3a0f6ef19afd
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/.swiftpm/xcode/xcshareddata/xcschemes/PetstoreClient.xcscheme
@@ -0,0 +1,67 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/Cartfile b/samples/client/petstore/swift6/alamofireLibrary/Cartfile
new file mode 100644
index 000000000000..2782bf6621ec
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/Cartfile
@@ -0,0 +1,2 @@
+github "Flight-School/AnyCodable" ~> 0.6
+github "Alamofire/Alamofire" ~> 5.9
diff --git a/samples/client/petstore/swift6/alamofireLibrary/Info.plist b/samples/client/petstore/swift6/alamofireLibrary/Info.plist
new file mode 100644
index 000000000000..323e5ecfc420
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/Info.plist
@@ -0,0 +1,22 @@
+
+
+
+
+ CFBundleDevelopmentRegion
+ $(DEVELOPMENT_LANGUAGE)
+ CFBundleExecutable
+ $(EXECUTABLE_NAME)
+ CFBundleIdentifier
+ $(PRODUCT_BUNDLE_IDENTIFIER)
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ $(PRODUCT_NAME)
+ CFBundlePackageType
+ FMWK
+ CFBundleShortVersionString
+ 1.0
+ CFBundleVersion
+ 1
+
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/Package.resolved b/samples/client/petstore/swift6/alamofireLibrary/Package.resolved
new file mode 100644
index 000000000000..e42b68f3b527
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/Package.resolved
@@ -0,0 +1,24 @@
+{
+ "originHash" : "8b2114c772cba9dfd29281c36d3097ab5d8bcb8eaf2c8fd299949087a48fd168",
+ "pins" : [
+ {
+ "identity" : "alamofire",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/Alamofire/Alamofire",
+ "state" : {
+ "revision" : "f455c2975872ccd2d9c81594c658af65716e9b9a",
+ "version" : "5.9.1"
+ }
+ },
+ {
+ "identity" : "anycodable",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/Flight-School/AnyCodable",
+ "state" : {
+ "revision" : "862808b2070cd908cb04f9aafe7de83d35f81b05",
+ "version" : "0.6.7"
+ }
+ }
+ ],
+ "version" : 3
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/Package.swift b/samples/client/petstore/swift6/alamofireLibrary/Package.swift
new file mode 100644
index 000000000000..3d83d131582e
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/Package.swift
@@ -0,0 +1,35 @@
+// swift-tools-version:6.0
+
+import PackageDescription
+
+let package = Package(
+ name: "PetstoreClient",
+ platforms: [
+ .iOS(.v12),
+ .macOS(.v10_13),
+ .tvOS(.v12),
+ .watchOS(.v4),
+ ],
+ products: [
+ // Products define the executables and libraries produced by a package, and make them visible to other packages.
+ .library(
+ name: "PetstoreClient",
+ targets: ["PetstoreClient"]
+ ),
+ ],
+ dependencies: [
+ // Dependencies declare other packages that this package depends on.
+ .package(url: "https://github.com/Flight-School/AnyCodable", .upToNextMajor(from: "0.6.7")),
+ .package(url: "https://github.com/Alamofire/Alamofire", .upToNextMajor(from: "5.9.1")),
+ ],
+ targets: [
+ // Targets are the basic building blocks of a package. A target can define a module or a test suite.
+ // Targets can depend on other targets in this package, and on products in packages which this package depends on.
+ .target(
+ name: "PetstoreClient",
+ dependencies: ["AnyCodable", "Alamofire", ],
+ path: "PetstoreClient/Classes"
+ ),
+ ],
+ swiftLanguageModes: [.v6]
+)
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient.podspec b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient.podspec
new file mode 100644
index 000000000000..6d65d90c82e3
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient.podspec
@@ -0,0 +1,16 @@
+Pod::Spec.new do |s|
+ s.name = 'PetstoreClient'
+ s.ios.deployment_target = '12.0'
+ s.osx.deployment_target = '10.13'
+ s.tvos.deployment_target = '12.0'
+ s.watchos.deployment_target = '4.0'
+ s.version = '1.0.0'
+ s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v1.0.0' }
+ s.authors = ''
+ s.license = 'Proprietary'
+ s.homepage = 'https://github.com/openapitools/openapi-generator'
+ s.summary = 'PetstoreClient'
+ s.source_files = 'PetstoreClient/Classes/**/*.swift'
+ s.dependency 'AnyCodable-FlightSchool', '~> 0.6'
+ s.dependency 'Alamofire', '~> 5.9'
+end
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift
new file mode 100644
index 000000000000..7c975bb6c9ba
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift
@@ -0,0 +1,121 @@
+// APIHelper.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+public struct APIHelper {
+ public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? {
+ let destination = source.reduce(into: [String: Any]()) { result, item in
+ if let value = item.value {
+ result[item.key] = value
+ }
+ }
+
+ if destination.isEmpty {
+ return nil
+ }
+ return destination
+ }
+
+ public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] {
+ return source.reduce(into: [String: String]()) { result, item in
+ if let collection = item.value as? [Any?] {
+ result[item.key] = collection
+ .compactMap { value in convertAnyToString(value) }
+ .joined(separator: ",")
+ } else if let value: Any = item.value {
+ result[item.key] = convertAnyToString(value)
+ }
+ }
+ }
+
+ public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? {
+ guard let source = source else {
+ return nil
+ }
+
+ return source.reduce(into: [String: Any]()) { result, item in
+ switch item.value {
+ case let x as Bool:
+ result[item.key] = x.description
+ default:
+ result[item.key] = item.value
+ }
+ }
+ }
+
+ public static func convertAnyToString(_ value: Any?) -> String? {
+ guard let value = value else { return nil }
+ if let value = value as? any RawRepresentable {
+ return "\(value.rawValue)"
+ } else {
+ return "\(value)"
+ }
+ }
+
+ public static func mapValueToPathItem(_ source: Any) -> Any {
+ if let collection = source as? [Any?] {
+ return collection
+ .compactMap { value in convertAnyToString(value) }
+ .joined(separator: ",")
+ } else if let value = source as? any RawRepresentable {
+ return "\(value.rawValue)"
+ }
+ return source
+ }
+
+ /// maps all values from source to query parameters
+ ///
+ /// explode attribute is respected: collection values might be either joined or split up into separate key value pairs
+ public static func mapValuesToQueryItems(_ source: [String: (wrappedValue: Any?, isExplode: Bool)]) -> [URLQueryItem]? {
+ let destination = source.filter { $0.value.wrappedValue != nil }.reduce(into: [URLQueryItem]()) { result, item in
+ if let collection = item.value.wrappedValue as? [Any?] {
+
+ let collectionValues: [String] = collection.compactMap { value in convertAnyToString(value) }
+
+ if !item.value.isExplode {
+ result.append(URLQueryItem(name: item.key, value: collectionValues.joined(separator: ",")))
+ } else {
+ collectionValues
+ .forEach { value in
+ result.append(URLQueryItem(name: item.key, value: value))
+ }
+ }
+
+ } else if let value = item.value.wrappedValue {
+ result.append(URLQueryItem(name: item.key, value: convertAnyToString(value)))
+ }
+ }
+
+ if destination.isEmpty {
+ return nil
+ }
+ return destination.sorted { $0.name < $1.name }
+ }
+
+ /// maps all values from source to query parameters
+ ///
+ /// collection values are always exploded
+ public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? {
+ let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in
+ if let collection = item.value as? [Any?] {
+ collection
+ .compactMap { value in convertAnyToString(value) }
+ .forEach { value in
+ result.append(URLQueryItem(name: item.key, value: value))
+ }
+
+ } else if let value = item.value {
+ result.append(URLQueryItem(name: item.key, value: convertAnyToString(value)))
+ }
+ }
+
+ if destination.isEmpty {
+ return nil
+ }
+ return destination.sorted { $0.name < $1.name }
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift
new file mode 100644
index 000000000000..140ba87dc4af
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs.swift
@@ -0,0 +1,85 @@
+// APIs.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+import Alamofire
+
+open class PetstoreClientAPI: @unchecked Sendable {
+ private init() {}
+ public static let shared = PetstoreClientAPI()
+
+ public var basePath = "http://petstore.swagger.io:80/v2"
+ public var customHeaders: [String: String] = [:]
+ public var credential: URLCredential?
+ public var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory()
+ public var apiResponseQueue: DispatchQueue = .main
+ /// Configures the range of HTTP status codes that will result in a successful response
+ ///
+ /// If a HTTP status code is outside of this range the response will be interpreted as failed.
+ public var successfulStatusCodeRange: Range = 200..<300
+ /// ResponseSerializer that will be used by the generator for `Data` responses
+ ///
+ /// If unchanged, Alamofires default `DataResponseSerializer` will be used.
+ public var dataResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(DataResponseSerializer())
+ /// ResponseSerializer that will be used by the generator for `String` responses
+ ///
+ /// If unchanged, Alamofires default `StringResponseSerializer` will be used.
+ public var stringResponseSerializer: AnyResponseSerializer = AnyResponseSerializer(StringResponseSerializer())
+}
+
+open class RequestBuilder: @unchecked Sendable {
+ var credential: URLCredential?
+ var headers: [String: String]
+ public let parameters: [String: Any]?
+ public let method: String
+ public let URLString: String
+ public let requestTask: RequestTask = RequestTask()
+ public let requiresAuthentication: Bool
+
+ /// Optional block to obtain a reference to the request's progress instance when available.
+ public var onProgressReady: ((Progress) -> Void)?
+
+ required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
+ self.method = method
+ self.URLString = URLString
+ self.parameters = parameters
+ self.headers = headers
+ self.requiresAuthentication = requiresAuthentication
+
+ addHeaders(PetstoreClientAPI.shared.customHeaders)
+ }
+
+ open func addHeaders(_ aHeaders: [String: String]) {
+ for (header, value) in aHeaders {
+ headers[header] = value
+ }
+ }
+
+ @discardableResult
+ open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, _ completion: @Sendable @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> RequestTask {
+ return requestTask
+ }
+
+ public func addHeader(name: String, value: String) -> Self {
+ if !value.isEmpty {
+ headers[name] = value
+ }
+ return self
+ }
+
+ open func addCredential() -> Self {
+ credential = PetstoreClientAPI.shared.credential
+ return self
+ }
+}
+
+public protocol RequestBuilderFactory {
+ func getNonDecodableBuilder() -> RequestBuilder.Type
+ func getBuilder() -> RequestBuilder.Type
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift
new file mode 100644
index 000000000000..ae7f51340cba
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift
@@ -0,0 +1,58 @@
+//
+// AnotherFakeAPI.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+open class AnotherFakeAPI {
+
+ /**
+ To test special tags
+
+ - parameter body: (body) client model
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Client?, _ error: Error?) -> Void) -> RequestTask {
+ return call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ To test special tags
+ - PATCH /another-fake/dummy
+ - To test special tags and operation ID starting with number
+ - parameter body: (body) client model
+ - returns: RequestBuilder
+ */
+ open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder {
+ let localVariablePath = "/another-fake/dummy"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/json",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift
new file mode 100644
index 000000000000..9820c2884343
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift
@@ -0,0 +1,699 @@
+//
+// FakeAPI.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+open class FakeAPI {
+
+ /**
+
+ - parameter body: (body) Input boolean as post body (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Bool?, _ error: Error?) -> Void) -> RequestTask {
+ return fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ - POST /fake/outer/boolean
+ - Test serialization of outer boolean types
+ - parameter body: (body) Input boolean as post body (optional)
+ - returns: RequestBuilder
+ */
+ open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder {
+ let localVariablePath = "/fake/outer/boolean"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+
+ - parameter body: (body) Input composite as post body (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: OuterComposite?, _ error: Error?) -> Void) -> RequestTask {
+ return fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ - POST /fake/outer/composite
+ - Test serialization of object with outer number type
+ - parameter body: (body) Input composite as post body (optional)
+ - returns: RequestBuilder
+ */
+ open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder {
+ let localVariablePath = "/fake/outer/composite"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+
+ - parameter body: (body) Input number as post body (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Double?, _ error: Error?) -> Void) -> RequestTask {
+ return fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ - POST /fake/outer/number
+ - Test serialization of outer number types
+ - parameter body: (body) Input number as post body (optional)
+ - returns: RequestBuilder
+ */
+ open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder {
+ let localVariablePath = "/fake/outer/number"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+
+ - parameter body: (body) Input string as post body (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: String?, _ error: Error?) -> Void) -> RequestTask {
+ return fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ - POST /fake/outer/string
+ - Test serialization of outer string types
+ - parameter body: (body) Input string as post body (optional)
+ - returns: RequestBuilder
+ */
+ open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder {
+ let localVariablePath = "/fake/outer/string"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+
+ - parameter body: (body)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ - PUT /fake/body-with-file-schema
+ - For this test, the body for this request much reference a schema named `File`.
+ - parameter body: (body)
+ - returns: RequestBuilder
+ */
+ open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder {
+ let localVariablePath = "/fake/body-with-file-schema"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/json",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+
+ - parameter query: (query)
+ - parameter body: (body)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ - PUT /fake/body-with-query-params
+ - parameter query: (query)
+ - parameter body: (body)
+ - returns: RequestBuilder
+ */
+ open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder {
+ let localVariablePath = "/fake/body-with-query-params"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ var localVariableUrlComponents = URLComponents(string: localVariableURLString)
+ localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
+ "query": (wrappedValue: query.encodeToJSON(), isExplode: false),
+ ])
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/json",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ To test \"client\" model
+
+ - parameter body: (body) client model
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Client?, _ error: Error?) -> Void) -> RequestTask {
+ return testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ To test \"client\" model
+ - PATCH /fake
+ - To test \"client\" model
+ - parameter body: (body) client model
+ - returns: RequestBuilder
+ */
+ open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder {
+ let localVariablePath = "/fake"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/json",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
+
+ - parameter number: (form) None
+ - parameter double: (form) None
+ - parameter patternWithoutDelimiter: (form) None
+ - parameter byte: (form) None
+ - parameter integer: (form) None (optional)
+ - parameter int32: (form) None (optional)
+ - parameter int64: (form) None (optional)
+ - parameter float: (form) None (optional)
+ - parameter string: (form) None (optional)
+ - parameter binary: (form) None (optional)
+ - parameter date: (form) None (optional)
+ - parameter dateTime: (form) None (optional)
+ - parameter password: (form) None (optional)
+ - parameter callback: (form) None (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: OpenAPIDateWithoutTime? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return testEndpointParametersWithRequestBuilder(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
+ - POST /fake
+ - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
+ - BASIC:
+ - type: http
+ - name: http_basic_test
+ - parameter number: (form) None
+ - parameter double: (form) None
+ - parameter patternWithoutDelimiter: (form) None
+ - parameter byte: (form) None
+ - parameter integer: (form) None (optional)
+ - parameter int32: (form) None (optional)
+ - parameter int64: (form) None (optional)
+ - parameter float: (form) None (optional)
+ - parameter string: (form) None (optional)
+ - parameter binary: (form) None (optional)
+ - parameter date: (form) None (optional)
+ - parameter dateTime: (form) None (optional)
+ - parameter password: (form) None (optional)
+ - parameter callback: (form) None (optional)
+ - returns: RequestBuilder
+ */
+ open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: OpenAPIDateWithoutTime? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder {
+ let localVariablePath = "/fake"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableFormParams: [String: Any?] = [
+ "integer": integer?.encodeToJSON(),
+ "int32": int32?.encodeToJSON(),
+ "int64": int64?.encodeToJSON(),
+ "number": number.encodeToJSON(),
+ "float": float?.encodeToJSON(),
+ "double": double.encodeToJSON(),
+ "string": string?.encodeToJSON(),
+ "pattern_without_delimiter": patternWithoutDelimiter.encodeToJSON(),
+ "byte": byte.encodeToJSON(),
+ "binary": binary?.encodeToJSON(),
+ "date": date?.encodeToJSON(),
+ "dateTime": dateTime?.encodeToJSON(),
+ "password": password?.encodeToJSON(),
+ "callback": callback?.encodeToJSON(),
+ ]
+
+ let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
+ let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/x-www-form-urlencoded",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ * enum for parameter enumHeaderStringArray
+ */
+ public enum EnumHeaderStringArray_testEnumParameters: String, CaseIterable {
+ case greaterThan = ">"
+ case dollar = "$"
+ }
+
+ /**
+ * enum for parameter enumHeaderString
+ */
+ public enum EnumHeaderString_testEnumParameters: String, CaseIterable {
+ case abc = "_abc"
+ case efg = "-efg"
+ case xyz = "(xyz)"
+ }
+
+ /**
+ * enum for parameter enumQueryStringArray
+ */
+ public enum EnumQueryStringArray_testEnumParameters: String, CaseIterable {
+ case greaterThan = ">"
+ case dollar = "$"
+ }
+
+ /**
+ * enum for parameter enumQueryString
+ */
+ public enum EnumQueryString_testEnumParameters: String, CaseIterable {
+ case abc = "_abc"
+ case efg = "-efg"
+ case xyz = "(xyz)"
+ }
+
+ /**
+ * enum for parameter enumQueryInteger
+ */
+ public enum EnumQueryInteger_testEnumParameters: Int, CaseIterable {
+ case _1 = 1
+ case number2 = -2
+ }
+
+ /**
+ * enum for parameter enumQueryDouble
+ */
+ public enum EnumQueryDouble_testEnumParameters: Double, CaseIterable {
+ case _11 = 1.1
+ case number12 = -1.2
+ }
+
+ /**
+ * enum for parameter enumFormStringArray
+ */
+ public enum EnumFormStringArray_testEnumParameters: String, CaseIterable {
+ case greaterThan = ">"
+ case dollar = "$"
+ }
+
+ /**
+ * enum for parameter enumFormString
+ */
+ public enum EnumFormString_testEnumParameters: String, CaseIterable {
+ case abc = "_abc"
+ case efg = "-efg"
+ case xyz = "(xyz)"
+ }
+
+ /**
+ To test enum parameters
+
+ - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional)
+ - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg)
+ - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional)
+ - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg)
+ - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional)
+ - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional)
+ - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar)
+ - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ To test enum parameters
+ - GET /fake
+ - To test enum parameters
+ - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional)
+ - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg)
+ - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional)
+ - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg)
+ - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional)
+ - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional)
+ - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar)
+ - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg)
+ - returns: RequestBuilder
+ */
+ open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder {
+ let localVariablePath = "/fake"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableFormParams: [String: Any?] = [
+ "enum_form_string_array": enumFormStringArray?.encodeToJSON(),
+ "enum_form_string": enumFormString?.encodeToJSON(),
+ ]
+
+ let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
+ let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
+
+ var localVariableUrlComponents = URLComponents(string: localVariableURLString)
+ localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
+ "enum_query_string_array": (wrappedValue: enumQueryStringArray?.encodeToJSON(), isExplode: false),
+ "enum_query_string": (wrappedValue: enumQueryString?.encodeToJSON(), isExplode: false),
+ "enum_query_integer": (wrappedValue: enumQueryInteger?.encodeToJSON(), isExplode: false),
+ "enum_query_double": (wrappedValue: enumQueryDouble?.encodeToJSON(), isExplode: false),
+ ])
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/x-www-form-urlencoded",
+ "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(),
+ "enum_header_string": enumHeaderString?.encodeToJSON(),
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Fake endpoint to test group parameters (optional)
+
+ - parameter requiredStringGroup: (query) Required String in group parameters
+ - parameter requiredBooleanGroup: (header) Required Boolean in group parameters
+ - parameter requiredInt64Group: (query) Required Integer in group parameters
+ - parameter stringGroup: (query) String in group parameters (optional)
+ - parameter booleanGroup: (header) Boolean in group parameters (optional)
+ - parameter int64Group: (query) Integer in group parameters (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Fake endpoint to test group parameters (optional)
+ - DELETE /fake
+ - Fake endpoint to test group parameters (optional)
+ - parameter requiredStringGroup: (query) Required String in group parameters
+ - parameter requiredBooleanGroup: (header) Required Boolean in group parameters
+ - parameter requiredInt64Group: (query) Required Integer in group parameters
+ - parameter stringGroup: (query) String in group parameters (optional)
+ - parameter booleanGroup: (header) Boolean in group parameters (optional)
+ - parameter int64Group: (query) Integer in group parameters (optional)
+ - returns: RequestBuilder
+ */
+ open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder {
+ let localVariablePath = "/fake"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ var localVariableUrlComponents = URLComponents(string: localVariableURLString)
+ localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
+ "required_string_group": (wrappedValue: requiredStringGroup.encodeToJSON(), isExplode: false),
+ "required_int64_group": (wrappedValue: requiredInt64Group.encodeToJSON(), isExplode: false),
+ "string_group": (wrappedValue: stringGroup?.encodeToJSON(), isExplode: false),
+ "int64_group": (wrappedValue: int64Group?.encodeToJSON(), isExplode: false),
+ ])
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "required_boolean_group": requiredBooleanGroup.encodeToJSON(),
+ "boolean_group": booleanGroup?.encodeToJSON(),
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ test inline additionalProperties
+
+ - parameter param: (body) request body
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ test inline additionalProperties
+ - POST /fake/inline-additionalProperties
+ - parameter param: (body) request body
+ - returns: RequestBuilder
+ */
+ open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder {
+ let localVariablePath = "/fake/inline-additionalProperties"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/json",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ test json serialization of form data
+
+ - parameter param: (form) field1
+ - parameter param2: (form) field2
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ test json serialization of form data
+ - GET /fake/jsonFormData
+ - parameter param: (form) field1
+ - parameter param2: (form) field2
+ - returns: RequestBuilder
+ */
+ open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder {
+ let localVariablePath = "/fake/jsonFormData"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableFormParams: [String: Any?] = [
+ "param": param.encodeToJSON(),
+ "param2": param2.encodeToJSON(),
+ ]
+
+ let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
+ let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/x-www-form-urlencoded",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift
new file mode 100644
index 000000000000..2a601f50172c
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift
@@ -0,0 +1,61 @@
+//
+// FakeClassnameTags123API.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+open class FakeClassnameTags123API {
+
+ /**
+ To test class name in snake case
+
+ - parameter body: (body) client model
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Client?, _ error: Error?) -> Void) -> RequestTask {
+ return testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ To test class name in snake case
+ - PATCH /fake_classname_test
+ - To test class name in snake case
+ - API Key:
+ - type: apiKey api_key_query (QUERY)
+ - name: api_key_query
+ - parameter body: (body) client model
+ - returns: RequestBuilder
+ */
+ open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder {
+ let localVariablePath = "/fake_classname_test"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/json",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift
new file mode 100644
index 000000000000..0bd82f5522eb
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift
@@ -0,0 +1,498 @@
+//
+// PetAPI.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+open class PetAPI {
+
+ /**
+ Add a new pet to the store
+
+ - parameter body: (body) Pet object that needs to be added to the store
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Add a new pet to the store
+ - POST /pet
+ - OAuth:
+ - type: oauth2
+ - name: petstore_auth
+ - API Key:
+ - type: apiKey api_key_query (QUERY)
+ - name: api_key_query
+ - parameter body: (body) Pet object that needs to be added to the store
+ - returns: RequestBuilder
+ */
+ open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder {
+ let localVariablePath = "/pet"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/json",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ Deletes a pet
+
+ - parameter petId: (path) Pet id to delete
+ - parameter apiKey: (header) (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func deletePet(petId: Int64, apiKey: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Deletes a pet
+ - DELETE /pet/{petId}
+ - OAuth:
+ - type: oauth2
+ - name: petstore_auth
+ - parameter petId: (path) Pet id to delete
+ - parameter apiKey: (header) (optional)
+ - returns: RequestBuilder
+ */
+ open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder {
+ var localVariablePath = "/pet/{petId}"
+ let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
+ let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "api_key": apiKey?.encodeToJSON(),
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ * enum for parameter status
+ */
+ public enum Status_findPetsByStatus: String, CaseIterable {
+ case available = "available"
+ case pending = "pending"
+ case sold = "sold"
+ }
+
+ /**
+ Finds Pets by status
+
+ - parameter status: (query) Status values that need to be considered for filter
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: [Pet]?, _ error: Error?) -> Void) -> RequestTask {
+ return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Finds Pets by status
+ - GET /pet/findByStatus
+ - Multiple status values can be provided with comma separated strings
+ - OAuth:
+ - type: oauth2
+ - name: petstore_auth
+ - parameter status: (query) Status values that need to be considered for filter
+ - returns: RequestBuilder<[Pet]>
+ */
+ open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> {
+ let localVariablePath = "/pet/findByStatus"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ var localVariableUrlComponents = URLComponents(string: localVariableURLString)
+ localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
+ "status": (wrappedValue: status.encodeToJSON(), isExplode: false),
+ ])
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ Finds Pets by tags
+
+ - parameter tags: (query) Tags to filter by
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @available(*, deprecated, message: "This operation is deprecated.")
+ @discardableResult
+ open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: [Pet]?, _ error: Error?) -> Void) -> RequestTask {
+ return findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Finds Pets by tags
+ - GET /pet/findByTags
+ - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
+ - OAuth:
+ - type: oauth2
+ - name: petstore_auth
+ - parameter tags: (query) Tags to filter by
+ - returns: RequestBuilder<[Pet]>
+ */
+ @available(*, deprecated, message: "This operation is deprecated.")
+ open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> {
+ let localVariablePath = "/pet/findByTags"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ var localVariableUrlComponents = URLComponents(string: localVariableURLString)
+ localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
+ "tags": (wrappedValue: tags.encodeToJSON(), isExplode: false),
+ ])
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ Find pet by ID
+
+ - parameter petId: (path) ID of pet to return
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Pet?, _ error: Error?) -> Void) -> RequestTask {
+ return getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Find pet by ID
+ - GET /pet/{petId}
+ - Returns a single pet
+ - API Key:
+ - type: apiKey api_key (HEADER)
+ - name: api_key
+ - parameter petId: (path) ID of pet to return
+ - returns: RequestBuilder
+ */
+ open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder {
+ var localVariablePath = "/pet/{petId}"
+ let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
+ let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ Update an existing pet
+
+ - parameter body: (body) Pet object that needs to be added to the store
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Update an existing pet
+ - PUT /pet
+ - OAuth:
+ - type: oauth2
+ - name: petstore_auth
+ - parameter body: (body) Pet object that needs to be added to the store
+ - returns: RequestBuilder
+ */
+ open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder {
+ let localVariablePath = "/pet"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/json",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ Updates a pet in the store with form data
+
+ - parameter petId: (path) ID of pet that needs to be updated
+ - parameter name: (form) Updated name of the pet (optional)
+ - parameter status: (form) Updated status of the pet (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Updates a pet in the store with form data
+ - POST /pet/{petId}
+ - OAuth:
+ - type: oauth2
+ - name: petstore_auth
+ - parameter petId: (path) ID of pet that needs to be updated
+ - parameter name: (form) Updated name of the pet (optional)
+ - parameter status: (form) Updated status of the pet (optional)
+ - returns: RequestBuilder
+ */
+ open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder {
+ var localVariablePath = "/pet/{petId}"
+ let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
+ let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableFormParams: [String: Any?] = [
+ "name": name?.encodeToJSON(),
+ "status": status?.encodeToJSON(),
+ ]
+
+ let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
+ let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "application/x-www-form-urlencoded",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ uploads an image
+
+ - parameter petId: (path) ID of pet to update
+ - parameter additionalMetadata: (form) Additional data to pass to server (optional)
+ - parameter file: (form) file to upload (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) -> RequestTask {
+ return uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ uploads an image
+ - POST /pet/{petId}/uploadImage
+ - OAuth:
+ - type: oauth2
+ - name: petstore_auth
+ - parameter petId: (path) ID of pet to update
+ - parameter additionalMetadata: (form) Additional data to pass to server (optional)
+ - parameter file: (form) file to upload (optional)
+ - returns: RequestBuilder
+ */
+ open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder {
+ var localVariablePath = "/pet/{petId}/uploadImage"
+ let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
+ let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableFormParams: [String: Any?] = [
+ "additionalMetadata": additionalMetadata?.encodeToJSON(),
+ "file": file?.encodeToJSON(),
+ ]
+
+ let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
+ let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "multipart/form-data",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ uploads an image (required)
+
+ - parameter petId: (path) ID of pet to update
+ - parameter requiredFile: (form) file to upload
+ - parameter additionalMetadata: (form) Additional data to pass to server (optional)
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func uploadFileWithRequiredFile(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) -> RequestTask {
+ return uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ uploads an image (required)
+ - POST /fake/{petId}/uploadImageWithRequiredFile
+ - OAuth:
+ - type: oauth2
+ - name: petstore_auth
+ - parameter petId: (path) ID of pet to update
+ - parameter requiredFile: (form) file to upload
+ - parameter additionalMetadata: (form) Additional data to pass to server (optional)
+ - returns: RequestBuilder
+ */
+ open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, requiredFile: URL, additionalMetadata: String? = nil) -> RequestBuilder {
+ var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile"
+ let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))"
+ let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableFormParams: [String: Any?] = [
+ "additionalMetadata": additionalMetadata?.encodeToJSON(),
+ "requiredFile": requiredFile.encodeToJSON(),
+ ]
+
+ let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams)
+ let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ "Content-Type": "multipart/form-data",
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift
new file mode 100644
index 000000000000..80d459964d41
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift
@@ -0,0 +1,196 @@
+//
+// StoreAPI.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+open class StoreAPI {
+
+ /**
+ Delete purchase order by ID
+
+ - parameter orderId: (path) ID of the order that needs to be deleted
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Delete purchase order by ID
+ - DELETE /store/order/{order_id}
+ - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
+ - parameter orderId: (path) ID of the order that needs to be deleted
+ - returns: RequestBuilder
+ */
+ open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder {
+ var localVariablePath = "/store/order/{order_id}"
+ let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))"
+ let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Returns pet inventories by status
+
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) -> RequestTask {
+ return getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Returns pet inventories by status
+ - GET /store/inventory
+ - Returns a map of status codes to quantities
+ - API Key:
+ - type: apiKey api_key (HEADER)
+ - name: api_key
+ - returns: RequestBuilder<[String: Int]>
+ */
+ open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> {
+ let localVariablePath = "/store/inventory"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true)
+ }
+
+ /**
+ Find purchase order by ID
+
+ - parameter orderId: (path) ID of pet that needs to be fetched
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Order?, _ error: Error?) -> Void) -> RequestTask {
+ return getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Find purchase order by ID
+ - GET /store/order/{order_id}
+ - For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions
+ - parameter orderId: (path) ID of pet that needs to be fetched
+ - returns: RequestBuilder
+ */
+ open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder {
+ var localVariablePath = "/store/order/{order_id}"
+ let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))"
+ let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Place an order for a pet
+
+ - parameter body: (body) order placed for purchasing the pet
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Order?, _ error: Error?) -> Void) -> RequestTask {
+ return placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Place an order for a pet
+ - POST /store/order
+ - parameter body: (body) order placed for purchasing the pet
+ - returns: RequestBuilder
+ */
+ open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder {
+ let localVariablePath = "/store/order"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift
new file mode 100644
index 000000000000..6682666b17c6
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift
@@ -0,0 +1,377 @@
+//
+// UserAPI.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+open class UserAPI {
+
+ /**
+ Create user
+
+ - parameter body: (body) Created user object
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Create user
+ - POST /user
+ - This can only be done by the logged in user.
+ - parameter body: (body) Created user object
+ - returns: RequestBuilder
+ */
+ open class func createUserWithRequestBuilder(body: User) -> RequestBuilder {
+ let localVariablePath = "/user"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Creates list of users with given input array
+
+ - parameter body: (body) List of user object
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Creates list of users with given input array
+ - POST /user/createWithArray
+ - parameter body: (body) List of user object
+ - returns: RequestBuilder
+ */
+ open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder {
+ let localVariablePath = "/user/createWithArray"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Creates list of users with given input array
+
+ - parameter body: (body) List of user object
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Creates list of users with given input array
+ - POST /user/createWithList
+ - parameter body: (body) List of user object
+ - returns: RequestBuilder
+ */
+ open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder {
+ let localVariablePath = "/user/createWithList"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Delete user
+
+ - parameter username: (path) The name that needs to be deleted
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Delete user
+ - DELETE /user/{username}
+ - This can only be done by the logged in user.
+ - parameter username: (path) The name that needs to be deleted
+ - returns: RequestBuilder
+ */
+ open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder {
+ var localVariablePath = "/user/{username}"
+ let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
+ let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Get user by user name
+
+ - parameter username: (path) The name that needs to be fetched. Use user1 for testing.
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: User?, _ error: Error?) -> Void) -> RequestTask {
+ return getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Get user by user name
+ - GET /user/{username}
+ - parameter username: (path) The name that needs to be fetched. Use user1 for testing.
+ - returns: RequestBuilder
+ */
+ open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder {
+ var localVariablePath = "/user/{username}"
+ let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
+ let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Logs user into the system
+
+ - parameter username: (query) The user name for login
+ - parameter password: (query) The password for login in clear text
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: String?, _ error: Error?) -> Void) -> RequestTask {
+ return loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in
+ switch result {
+ case let .success(response):
+ completion(response.body, nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Logs user into the system
+ - GET /user/login
+ - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)]
+ - parameter username: (query) The user name for login
+ - parameter password: (query) The password for login in clear text
+ - returns: RequestBuilder
+ */
+ open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder {
+ let localVariablePath = "/user/login"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ var localVariableUrlComponents = URLComponents(string: localVariableURLString)
+ localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([
+ "username": (wrappedValue: username.encodeToJSON(), isExplode: false),
+ "password": (wrappedValue: password.encodeToJSON(), isExplode: false),
+ ])
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Logs out current logged in user session
+
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return logoutUserWithRequestBuilder().execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Logs out current logged in user session
+ - GET /user/logout
+ - returns: RequestBuilder
+ */
+ open class func logoutUserWithRequestBuilder() -> RequestBuilder {
+ let localVariablePath = "/user/logout"
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters: [String: Any]? = nil
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+
+ /**
+ Updated user
+
+ - parameter username: (path) name that need to be deleted
+ - parameter body: (body) Updated user object
+ - parameter apiResponseQueue: The queue on which api response is dispatched.
+ - parameter completion: completion handler to receive the data and the error objects
+ */
+ @discardableResult
+ open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, completion: @Sendable @escaping (_ data: Void?, _ error: Error?) -> Void) -> RequestTask {
+ return updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result in
+ switch result {
+ case .success:
+ completion((), nil)
+ case let .failure(error):
+ completion(nil, error)
+ }
+ }
+ }
+
+ /**
+ Updated user
+ - PUT /user/{username}
+ - This can only be done by the logged in user.
+ - parameter username: (path) name that need to be deleted
+ - parameter body: (body) Updated user object
+ - returns: RequestBuilder
+ */
+ open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder {
+ var localVariablePath = "/user/{username}"
+ let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))"
+ let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? ""
+ localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil)
+ let localVariableURLString = PetstoreClientAPI.shared.basePath + localVariablePath
+ let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body)
+
+ let localVariableUrlComponents = URLComponents(string: localVariableURLString)
+
+ let localVariableNillableHeaders: [String: Any?] = [
+ :
+ ]
+
+ let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders)
+
+ let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.shared.requestBuilderFactory.getNonDecodableBuilder()
+
+ return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: false)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift
new file mode 100644
index 000000000000..a597437ab5a8
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift
@@ -0,0 +1,418 @@
+// AlamofireImplementations.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+import Alamofire
+
+class AlamofireRequestBuilderFactory: RequestBuilderFactory {
+ func getNonDecodableBuilder() -> RequestBuilder.Type {
+ return AlamofireRequestBuilder.self
+ }
+
+ func getBuilder() -> RequestBuilder.Type {
+ return AlamofireDecodableRequestBuilder.self
+ }
+}
+
+fileprivate class AlamofireRequestBuilderConfiguration: @unchecked Sendable {
+ private init() {}
+ static let shared = AlamofireRequestBuilderConfiguration()
+
+ // Store manager to retain its reference
+ var managerStore = SynchronizedDictionary()
+}
+
+open class AlamofireRequestBuilder: RequestBuilder, @unchecked Sendable {
+ required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:], requiresAuthentication: Bool) {
+ super.init(method: method, URLString: URLString, parameters: parameters, headers: headers, requiresAuthentication: requiresAuthentication)
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the session
+ configuration.
+ */
+ open func createAlamofireSession(interceptor: RequestInterceptor? = nil) -> Alamofire.Session {
+ let configuration = URLSessionConfiguration.default
+ configuration.httpAdditionalHeaders = buildHeaders()
+ return Alamofire.Session(configuration: configuration,
+ interceptor: interceptor)
+ }
+
+ /**
+ May be overridden by a subclass if you want to custom request constructor.
+ */
+ open func createURLRequest() -> URLRequest? {
+ let xMethod = Alamofire.HTTPMethod(rawValue: method)
+
+ let encoding: ParameterEncoding
+
+ switch xMethod {
+ case .get, .head:
+ encoding = URLEncoding()
+
+ case .options, .post, .put, .patch, .delete, .trace, .connect:
+ encoding = JSONDataEncoding()
+
+ default:
+ fatalError("Unsupported HTTPMethod - \(xMethod.rawValue)")
+ }
+
+ guard let originalRequest = try? URLRequest(url: URLString, method: xMethod, headers: HTTPHeaders(buildHeaders())) else { return nil }
+ return try? encoding.encode(originalRequest, with: parameters)
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the Content-Type
+ that is given to an uploaded form part.
+
+ Return nil to use the default behavior (inferring the Content-Type from
+ the file extension). Return the desired Content-Type otherwise.
+ */
+ open func contentTypeForFormPart(fileURL: URL) -> String? {
+ return nil
+ }
+
+ /**
+ May be overridden by a subclass if you want to control the request
+ configuration (e.g. to override the cache policy).
+ */
+ open func makeRequest(manager: Session, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) -> DataRequest {
+ return manager.request(URLString, method: method, parameters: parameters, encoding: encoding, headers: HTTPHeaders(headers))
+ }
+
+ @discardableResult
+ override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.shared.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> RequestTask {
+ let managerId = UUID().uuidString
+ // Create a new manager for each request to customize its request header
+ let manager = createAlamofireSession()
+ AlamofireRequestBuilderConfiguration.shared.managerStore[managerId] = manager
+
+ let xMethod = Alamofire.HTTPMethod(rawValue: method)
+
+ let encoding: ParameterEncoding?
+
+ switch xMethod {
+ case .get, .head:
+ encoding = URLEncoding()
+
+ case .options, .post, .put, .patch, .delete, .trace, .connect:
+ let contentType = headers["Content-Type"] ?? "application/json"
+
+ if contentType.hasPrefix("application/") && contentType.contains("json") {
+ encoding = JSONDataEncoding()
+ } else if contentType.hasPrefix("multipart/form-data") {
+ encoding = nil
+
+ let upload = manager.upload(multipartFormData: { mpForm in
+ for (k, v) in self.parameters! {
+ for v in (v as? Array ?? [v]) {
+ switch v {
+ case let fileURL as URL:
+ if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) {
+ mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType)
+ } else {
+ mpForm.append(fileURL, withName: k)
+ }
+ case let string as String:
+ mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k)
+ case let number as NSNumber:
+ mpForm.append(number.stringValue.data(using: String.Encoding.utf8)!, withName: k)
+ case let data as Data:
+ mpForm.append(data, withName: k)
+ case let uuid as UUID:
+ mpForm.append(uuid.uuidString.data(using: String.Encoding.utf8)!, withName: k)
+ default:
+ fatalError("Unprocessable value \(v) with key \(k)")
+ }
+ }
+ }
+ }, to: URLString, method: xMethod, headers: nil)
+ .uploadProgress { progress in
+ if let onProgressReady = self.onProgressReady {
+ onProgressReady(progress)
+ }
+ }
+
+ requestTask.set(request: upload)
+
+ self.processRequest(request: upload, managerId, apiResponseQueue, completion)
+ } else if contentType.hasPrefix("application/x-www-form-urlencoded") {
+ encoding = URLEncoding(destination: .httpBody)
+ } else {
+ fatalError("Unsupported Media Type - \(contentType)")
+ }
+
+ default:
+ fatalError("Unsupported HTTPMethod - \(xMethod.rawValue)")
+ }
+
+ if let encoding = encoding {
+ let request = makeRequest(manager: manager, method: xMethod, encoding: encoding, headers: headers)
+ if let onProgressReady = self.onProgressReady {
+ onProgressReady(request.uploadProgress)
+ }
+ processRequest(request: request, managerId, apiResponseQueue, completion)
+ requestTask.set(request: request)
+ }
+
+ return requestTask
+ }
+
+ fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) {
+ if let credential = self.credential {
+ request.authenticate(with: credential)
+ }
+
+ let cleanupRequest = {
+ AlamofireRequestBuilderConfiguration.shared.managerStore[managerId] = nil
+ }
+
+ let validatedRequest = request.validate(statusCode: PetstoreClientAPI.shared.successfulStatusCodeRange)
+
+ switch T.self {
+ case is Void.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: PetstoreClientAPI.shared.dataResponseSerializer,
+ completionHandler: { voidResponse in
+ cleanupRequest()
+
+ switch voidResponse.result {
+ case .success:
+ completion(.success(Response(response: voidResponse.response!, body: () as! T, bodyData: voidResponse.data)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error)))
+ }
+
+ })
+ default:
+ fatalError("Unsupported Response Body Type - \(String(describing: T.self))")
+ }
+ }
+
+ open func buildHeaders() -> [String: String] {
+ var httpHeaders = Alamofire.HTTPHeaders.default.dictionary
+ for (key, value) in headers {
+ httpHeaders[key] = value
+ }
+ return httpHeaders
+ }
+
+ fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? {
+
+ guard let contentDisposition = contentDisposition else {
+ return nil
+ }
+
+ let items = contentDisposition.components(separatedBy: ";")
+
+ var filename: String?
+
+ for contentItem in items {
+
+ let filenameKey = "filename="
+ guard let range = contentItem.range(of: filenameKey) else {
+ continue
+ }
+
+ filename = contentItem
+ return filename?
+ .replacingCharacters(in: range, with: "")
+ .replacingOccurrences(of: "\"", with: "")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ }
+
+ return filename
+
+ }
+
+ fileprivate func getPath(from url: URL) throws -> String {
+
+ guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else {
+ throw DownloadException.requestMissingPath
+ }
+
+ if path.hasPrefix("/") {
+ path.remove(at: path.startIndex)
+ }
+
+ return path
+
+ }
+
+ fileprivate func getURL(from urlRequest: URLRequest) throws -> URL {
+
+ guard let url = urlRequest.url else {
+ throw DownloadException.requestMissingURL
+ }
+
+ return url
+ }
+
+}
+
+open class AlamofireDecodableRequestBuilder: AlamofireRequestBuilder, @unchecked Sendable {
+
+ override fileprivate func processRequest(request: DataRequest, _ managerId: String, _ apiResponseQueue: DispatchQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) {
+ if let credential = self.credential {
+ request.authenticate(with: credential)
+ }
+
+ let cleanupRequest = {
+ AlamofireRequestBuilderConfiguration.shared.managerStore[managerId] = nil
+ }
+
+ let validatedRequest = request.validate(statusCode: PetstoreClientAPI.shared.successfulStatusCodeRange)
+
+ switch T.self {
+ case is String.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: PetstoreClientAPI.shared.stringResponseSerializer,
+ completionHandler: { stringResponse in
+ cleanupRequest()
+
+ switch stringResponse.result {
+ case let .success(value):
+ completion(.success(Response(response: stringResponse.response!, body: value as! T, bodyData: stringResponse.data)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error)))
+ }
+
+ })
+ case is URL.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: PetstoreClientAPI.shared.dataResponseSerializer,
+ completionHandler: { dataResponse in
+ cleanupRequest()
+
+ do {
+
+ guard case .success = dataResponse.result else {
+ throw DownloadException.responseFailed
+ }
+
+ guard let data = dataResponse.data else {
+ throw DownloadException.responseDataMissing
+ }
+
+ guard let request = request.request else {
+ throw DownloadException.requestMissing
+ }
+
+ let fileManager = FileManager.default
+ let urlRequest = try request.asURLRequest()
+ let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
+ let requestURL = try self.getURL(from: urlRequest)
+
+ var requestPath = try self.getPath(from: requestURL)
+
+ if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) {
+ requestPath = requestPath.appending("/\(headerFileName)")
+ } else {
+ requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)")
+ }
+
+ let filePath = cachesDirectory.appendingPathComponent(requestPath)
+ let directoryPath = filePath.deletingLastPathComponent().path
+
+ try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil)
+ try data.write(to: filePath, options: .atomic)
+
+ completion(.success(Response(response: dataResponse.response!, body: filePath as! T, bodyData: data)))
+
+ } catch let requestParserError as DownloadException {
+ completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError)))
+ } catch {
+ completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, error)))
+ }
+ return
+ })
+ case is Void.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: PetstoreClientAPI.shared.dataResponseSerializer,
+ completionHandler: { voidResponse in
+ cleanupRequest()
+
+ switch voidResponse.result {
+ case .success:
+ completion(.success(Response(response: voidResponse.response!, body: () as! T, bodyData: voidResponse.data)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error)))
+ }
+
+ })
+ case is Data.Type:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: PetstoreClientAPI.shared.dataResponseSerializer,
+ completionHandler: { dataResponse in
+ cleanupRequest()
+
+ switch dataResponse.result {
+ case .success:
+ completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as! T, bodyData: dataResponse.data)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error)))
+ }
+
+ })
+ default:
+ validatedRequest.response(queue: apiResponseQueue,
+ responseSerializer: PetstoreClientAPI.shared.dataResponseSerializer,
+ completionHandler: { dataResponse in
+ cleanupRequest()
+
+ if case let .failure(error) = dataResponse.result {
+ completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error)))
+ return
+ }
+
+ guard let httpResponse = dataResponse.response else {
+ completion(.failure(ErrorResponse.error(-2, nil, dataResponse.response, DecodableRequestBuilderError.nilHTTPResponse)))
+ return
+ }
+
+ guard let unwrappedData = dataResponse.data, !unwrappedData.isEmpty else {
+ if let expressibleByNilLiteralType = T.self as? ExpressibleByNilLiteral.Type {
+ completion(.success(Response(response: httpResponse, body: expressibleByNilLiteralType.init(nilLiteral: ()) as! T, bodyData: dataResponse.data)))
+ } else {
+ completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, httpResponse, DecodableRequestBuilderError.emptyDataResponse)))
+ }
+ return
+ }
+
+ let decodeResult = CodableHelper.shared.decode(T.self, from: unwrappedData)
+
+ switch decodeResult {
+ case let .success(decodableObj):
+ completion(.success(Response(response: httpResponse, body: decodableObj, bodyData: unwrappedData)))
+ case let .failure(error):
+ completion(.failure(ErrorResponse.error(httpResponse.statusCode, unwrappedData, httpResponse, error)))
+ }
+
+ })
+ }
+ }
+
+}
+
+extension JSONDataEncoding: ParameterEncoding {
+
+ // MARK: Encoding
+
+ /// Creates a URL request by encoding parameters and applying them onto an existing request.
+ ///
+ /// - parameter urlRequest: The request to have parameters applied.
+ /// - parameter parameters: The parameters to apply. This should have a single key/value
+ /// pair with "jsonData" as the key and a Data object as the value.
+ ///
+ /// - throws: An `Error` if the encoding process encounters an error.
+ ///
+ /// - returns: The encoded request.
+ public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
+ let urlRequest = try urlRequest.asURLRequest()
+
+ return encode(urlRequest, with: parameters)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift
new file mode 100644
index 000000000000..a7f28f12a307
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift
@@ -0,0 +1,52 @@
+//
+// CodableHelper.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+open class CodableHelper: @unchecked Sendable {
+ private init() {}
+ public static let shared = CodableHelper()
+
+ private var customDateFormatter: DateFormatter?
+ private var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter()
+
+ private var customJSONDecoder: JSONDecoder?
+ private lazy var defaultJSONDecoder: JSONDecoder = {
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .formatted(dateFormatter)
+ return decoder
+ }()
+
+ private var customJSONEncoder: JSONEncoder?
+ private lazy var defaultJSONEncoder: JSONEncoder = {
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .formatted(dateFormatter)
+ encoder.outputFormatting = .prettyPrinted
+ return encoder
+ }()
+
+ public var dateFormatter: DateFormatter {
+ get { return customDateFormatter ?? defaultDateFormatter }
+ set { customDateFormatter = newValue }
+ }
+ public var jsonDecoder: JSONDecoder {
+ get { return customJSONDecoder ?? defaultJSONDecoder }
+ set { customJSONDecoder = newValue }
+ }
+ public var jsonEncoder: JSONEncoder {
+ get { return customJSONEncoder ?? defaultJSONEncoder }
+ set { customJSONEncoder = newValue }
+ }
+
+ open func decode(_ type: T.Type, from data: Data) -> Swift.Result where T: Decodable {
+ return Swift.Result { try jsonDecoder.decode(type, from: data) }
+ }
+
+ open func encode(_ value: T) -> Swift.Result where T: Encodable {
+ return Swift.Result { try jsonEncoder.encode(value) }
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift
new file mode 100644
index 000000000000..f979c1da7855
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift
@@ -0,0 +1,236 @@
+// Extensions.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+extension Bool: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Float: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Int: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Int32: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Int64: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Double: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension Decimal: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension String: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension URL: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension UUID: JSONEncodable {
+ func encodeToJSON() -> Any { self }
+}
+
+extension RawRepresentable where RawValue: JSONEncodable {
+ func encodeToJSON() -> Any { return self.rawValue }
+}
+
+private func encodeIfPossible(_ object: T) -> Any {
+ if let encodableObject = object as? JSONEncodable {
+ return encodableObject.encodeToJSON()
+ } else {
+ return object
+ }
+}
+
+extension Array: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return self.map(encodeIfPossible)
+ }
+}
+
+extension Set: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return Array(self).encodeToJSON()
+ }
+}
+
+extension Dictionary: JSONEncodable {
+ func encodeToJSON() -> Any {
+ var dictionary = [AnyHashable: Any]()
+ for (key, value) in self {
+ dictionary[key] = encodeIfPossible(value)
+ }
+ return dictionary
+ }
+}
+
+extension Data: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return self.base64EncodedString(options: Data.Base64EncodingOptions())
+ }
+}
+
+extension Date: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return CodableHelper.shared.dateFormatter.string(from: self)
+ }
+}
+
+extension JSONEncodable where Self: Encodable {
+ func encodeToJSON() -> Any {
+ guard let data = try? CodableHelper.shared.jsonEncoder.encode(self) else {
+ fatalError("Could not encode to json: \(self)")
+ }
+ return data.encodeToJSON()
+ }
+}
+
+extension String: @retroactive CodingKey {
+
+ public var stringValue: String {
+ return self
+ }
+
+ public init?(stringValue: String) {
+ self.init(stringLiteral: stringValue)
+ }
+
+ public var intValue: Int? {
+ return nil
+ }
+
+ public init?(intValue: Int) {
+ return nil
+ }
+
+}
+
+extension KeyedEncodingContainerProtocol {
+
+ public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable {
+ var arrayContainer = nestedUnkeyedContainer(forKey: key)
+ try arrayContainer.encode(contentsOf: values)
+ }
+
+ public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable {
+ if let values = values {
+ try encodeArray(values, forKey: key)
+ }
+ }
+
+ public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable {
+ for (key, value) in pairs {
+ try encode(value, forKey: key)
+ }
+ }
+
+ public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable {
+ if let pairs = pairs {
+ try encodeMap(pairs)
+ }
+ }
+
+ public mutating func encode(_ value: Decimal, forKey key: Self.Key) throws {
+ let decimalNumber = NSDecimalNumber(decimal: value)
+ let numberFormatter = NumberFormatter()
+ numberFormatter.numberStyle = .decimal
+ numberFormatter.locale = Locale(identifier: "en_US")
+ let formattedString = numberFormatter.string(from: decimalNumber) ?? "\(value)"
+ try encode(formattedString, forKey: key)
+ }
+
+ public mutating func encodeIfPresent(_ value: Decimal?, forKey key: Self.Key) throws {
+ if let value = value {
+ try encode(value, forKey: key)
+ }
+ }
+}
+
+extension KeyedDecodingContainerProtocol {
+
+ public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable {
+ var tmpArray = [T]()
+
+ var nestedContainer = try nestedUnkeyedContainer(forKey: key)
+ while !nestedContainer.isAtEnd {
+ let arrayValue = try nestedContainer.decode(T.self)
+ tmpArray.append(arrayValue)
+ }
+
+ return tmpArray
+ }
+
+ public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable {
+ var tmpArray: [T]?
+
+ if contains(key) {
+ tmpArray = try decodeArray(T.self, forKey: key)
+ }
+
+ return tmpArray
+ }
+
+ public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable {
+ var map: [Self.Key: T] = [:]
+
+ for key in allKeys {
+ if !excludedKeys.contains(key) {
+ let value = try decode(T.self, forKey: key)
+ map[key] = value
+ }
+ }
+
+ return map
+ }
+
+ public func decode(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal {
+ let stringValue = try decode(String.self, forKey: key)
+ guard let decimalValue = Decimal(string: stringValue) else {
+ let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
+ throw DecodingError.typeMismatch(type, context)
+ }
+
+ return decimalValue
+ }
+
+ public func decodeIfPresent(_ type: Decimal.Type, forKey key: Self.Key) throws -> Decimal? {
+ guard let stringValue = try decodeIfPresent(String.self, forKey: key) else {
+ return nil
+ }
+ guard let decimalValue = Decimal(string: stringValue) else {
+ let context = DecodingError.Context(codingPath: [key], debugDescription: "The key \(key) couldn't be converted to a Decimal value")
+ throw DecodingError.typeMismatch(type, context)
+ }
+
+ return decimalValue
+ }
+
+}
+
+extension HTTPURLResponse {
+ var isStatusCodeSuccessful: Bool {
+ return PetstoreClientAPI.shared.successfulStatusCodeRange.contains(statusCode)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift
new file mode 100644
index 000000000000..cb3121a4f632
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift
@@ -0,0 +1,56 @@
+//
+// JSONDataEncoding.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+
+public struct JSONDataEncoding {
+
+ // MARK: Properties
+
+ private static let jsonDataKey = "jsonData"
+
+ // MARK: Encoding
+
+ /// Creates a URL request by encoding parameters and applying them onto an existing request.
+ ///
+ /// - parameter urlRequest: The request to have parameters applied.
+ /// - parameter parameters: The parameters to apply. This should have a single key/value
+ /// pair with "jsonData" as the key and a Data object as the value.
+ ///
+ /// - throws: An `Error` if the encoding process encounters an error.
+ ///
+ /// - returns: The encoded request.
+ public func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest {
+ var urlRequest = urlRequest
+
+ guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else {
+ return urlRequest
+ }
+
+ if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
+ urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ }
+
+ urlRequest.httpBody = jsonData
+
+ return urlRequest
+ }
+
+ public static func encodingParameters(jsonData: Data?) -> [String: Any]? {
+ var returnedParams: [String: Any]?
+ if let jsonData = jsonData, !jsonData.isEmpty {
+ var params: [String: Any] = [:]
+ params[jsonDataKey] = jsonData
+ returnedParams = params
+ }
+ return returnedParams
+ }
+
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift
new file mode 100644
index 000000000000..95d1f869db90
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift
@@ -0,0 +1,45 @@
+//
+// JSONEncodingHelper.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+open class JSONEncodingHelper {
+
+ open class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? {
+ var params: [String: Any]?
+
+ // Encode the Encodable object
+ if let encodableObj = encodableObj {
+ let encodeResult = CodableHelper.shared.encode(encodableObj)
+ do {
+ let data = try encodeResult.get()
+ params = JSONDataEncoding.encodingParameters(jsonData: data)
+ } catch {
+ print(error.localizedDescription)
+ }
+ }
+
+ return params
+ }
+
+ open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? {
+ var params: [String: Any]?
+
+ if let encodableObj = encodableObj {
+ do {
+ let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted)
+ params = JSONDataEncoding.encodingParameters(jsonData: data)
+ } catch {
+ print(error.localizedDescription)
+ return nil
+ }
+ }
+
+ return params
+ }
+
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift
new file mode 100644
index 000000000000..6dc54ffd2889
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift
@@ -0,0 +1,152 @@
+// Models.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(FoundationNetworking)
+import FoundationNetworking
+#endif
+import Alamofire
+
+protocol JSONEncodable {
+ func encodeToJSON() -> Any
+}
+
+/// An enum where the last case value can be used as a default catch-all.
+protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable
+where RawValue: Decodable, AllCases: BidirectionalCollection {}
+
+extension CaseIterableDefaultsLast {
+ /// Initializes an enum such that if a known raw value is found, then it is decoded.
+ /// Otherwise the last case is used.
+ /// - Parameter decoder: A decoder.
+ public init(from decoder: Decoder) throws {
+ if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) {
+ self = value
+ } else if let lastValue = Self.allCases.last {
+ self = lastValue
+ } else {
+ throw DecodingError.valueNotFound(
+ Self.Type.self,
+ .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast")
+ )
+ }
+ }
+}
+
+/// A flexible type that can be encoded (`.encodeNull` or `.encodeValue`)
+/// or not encoded (`.encodeNothing`). Intended for request payloads.
+public enum NullEncodable: Hashable {
+ case encodeNothing
+ case encodeNull
+ case encodeValue(Wrapped)
+}
+
+extension NullEncodable: Codable where Wrapped: Codable {
+ public init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+ if let value = try? container.decode(Wrapped.self) {
+ self = .encodeValue(value)
+ } else if container.decodeNil() {
+ self = .encodeNull
+ } else {
+ self = .encodeNothing
+ }
+ }
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ switch self {
+ case .encodeNothing: return
+ case .encodeNull: try container.encodeNil()
+ case .encodeValue(let wrapped): try container.encode(wrapped)
+ }
+ }
+}
+
+public enum ErrorResponse: Error {
+ case error(Int, Data?, URLResponse?, Error)
+}
+
+public enum DownloadException: Error {
+ case responseDataMissing
+ case responseFailed
+ case requestMissing
+ case requestMissingPath
+ case requestMissingURL
+}
+
+public enum DecodableRequestBuilderError: Error {
+ case emptyDataResponse
+ case nilHTTPResponse
+ case unsuccessfulHTTPStatusCode
+ case jsonDecoding(DecodingError)
+ case generalError(Error)
+}
+
+open class Response {
+ public let statusCode: Int
+ public let header: [String: String]
+ public let body: T
+ public let bodyData: Data?
+
+ public init(statusCode: Int, header: [String: String], body: T, bodyData: Data?) {
+ self.statusCode = statusCode
+ self.header = header
+ self.body = body
+ self.bodyData = bodyData
+ }
+
+ public convenience init(response: HTTPURLResponse, body: T, bodyData: Data?) {
+ let rawHeader = response.allHeaderFields
+ var responseHeader = [String: String]()
+ for (key, value) in rawHeader {
+ if let key = key.base as? String, let value = value as? String {
+ responseHeader[key] = value
+ }
+ }
+ self.init(statusCode: response.statusCode, header: responseHeader, body: body, bodyData: bodyData)
+ }
+}
+
+/// Type-erased ResponseSerializer
+///
+/// This is needed in order to use `ResponseSerializer` as a Type in `Configuration`. Obsolete with `any` keyword in Swift >= 5.7
+public struct AnyResponseSerializer: ResponseSerializer {
+
+ let _serialize: (URLRequest?, HTTPURLResponse?, Data?, Error?) throws -> T
+
+ public init(_ delegatee: V) where V.SerializedObject == T {
+ _serialize = delegatee.serialize
+ }
+
+ public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> T {
+ try _serialize(request, response, data, error)
+ }
+}
+
+public final class RequestTask {
+ private var lock = NSRecursiveLock()
+ private var request: Request?
+
+ internal func set(request: Request) {
+ lock.withLock {
+ self.request = request
+ }
+ }
+
+ internal func get() -> Request? {
+ lock.withLock {
+ request
+ }
+ }
+
+ public func cancel() {
+ lock.withLock {
+ request?.cancel()
+ request = nil
+ }
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift
new file mode 100644
index 000000000000..623c4c7fd2c4
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift
@@ -0,0 +1,36 @@
+//
+// AdditionalPropertiesClass.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct AdditionalPropertiesClass: Codable, JSONEncodable, Hashable {
+
+ public var mapString: [String: String]?
+ public var mapMapString: [String: [String: String]]?
+
+ public init(mapString: [String: String]? = nil, mapMapString: [String: [String: String]]? = nil) {
+ self.mapString = mapString
+ self.mapMapString = mapMapString
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case mapString = "map_string"
+ case mapMapString = "map_map_string"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(mapString, forKey: .mapString)
+ try container.encodeIfPresent(mapMapString, forKey: .mapMapString)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift
new file mode 100644
index 000000000000..a6882d6517fd
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift
@@ -0,0 +1,36 @@
+//
+// Animal.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Animal: Codable, JSONEncodable, Hashable {
+
+ public var className: String
+ public var color: String? = "red"
+
+ public init(className: String, color: String? = "red") {
+ self.className = className
+ self.color = color
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case className
+ case color
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(className, forKey: .className)
+ try container.encodeIfPresent(color, forKey: .color)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift
new file mode 100644
index 000000000000..a0b09cb97615
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift
@@ -0,0 +1,13 @@
+//
+// AnimalFarm.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public typealias AnimalFarm = [Animal]
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift
new file mode 100644
index 000000000000..1890fcf9fde7
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift
@@ -0,0 +1,40 @@
+//
+// ApiResponse.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct ApiResponse: Codable, JSONEncodable, Hashable {
+
+ public var code: Int?
+ public var type: String?
+ public var message: String?
+
+ public init(code: Int? = nil, type: String? = nil, message: String? = nil) {
+ self.code = code
+ self.type = type
+ self.message = message
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case code
+ case type
+ case message
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(code, forKey: .code)
+ try container.encodeIfPresent(type, forKey: .type)
+ try container.encodeIfPresent(message, forKey: .message)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift
new file mode 100644
index 000000000000..eabae42d3bf4
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift
@@ -0,0 +1,32 @@
+//
+// ArrayOfArrayOfNumberOnly.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct ArrayOfArrayOfNumberOnly: Codable, JSONEncodable, Hashable {
+
+ public var arrayArrayNumber: [[Double]]?
+
+ public init(arrayArrayNumber: [[Double]]? = nil) {
+ self.arrayArrayNumber = arrayArrayNumber
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case arrayArrayNumber = "ArrayArrayNumber"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift
new file mode 100644
index 000000000000..fa93d7c6c743
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift
@@ -0,0 +1,32 @@
+//
+// ArrayOfNumberOnly.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct ArrayOfNumberOnly: Codable, JSONEncodable, Hashable {
+
+ public var arrayNumber: [Double]?
+
+ public init(arrayNumber: [Double]? = nil) {
+ self.arrayNumber = arrayNumber
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case arrayNumber = "ArrayNumber"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift
new file mode 100644
index 000000000000..c99f82be9b93
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift
@@ -0,0 +1,40 @@
+//
+// ArrayTest.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct ArrayTest: Codable, JSONEncodable, Hashable {
+
+ public var arrayOfString: [String]?
+ public var arrayArrayOfInteger: [[Int64]]?
+ public var arrayArrayOfModel: [[ReadOnlyFirst]]?
+
+ public init(arrayOfString: [String]? = nil, arrayArrayOfInteger: [[Int64]]? = nil, arrayArrayOfModel: [[ReadOnlyFirst]]? = nil) {
+ self.arrayOfString = arrayOfString
+ self.arrayArrayOfInteger = arrayArrayOfInteger
+ self.arrayArrayOfModel = arrayArrayOfModel
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case arrayOfString = "array_of_string"
+ case arrayArrayOfInteger = "array_array_of_integer"
+ case arrayArrayOfModel = "array_array_of_model"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString)
+ try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger)
+ try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift
new file mode 100644
index 000000000000..f8a3f64e2ee8
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift
@@ -0,0 +1,53 @@
+//
+// Capitalization.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Capitalization: Codable, JSONEncodable, Hashable {
+
+ public var smallCamel: String?
+ public var capitalCamel: String?
+ public var smallSnake: String?
+ public var capitalSnake: String?
+ public var sCAETHFlowPoints: String?
+ /** Name of the pet */
+ public var ATT_NAME: String?
+
+ public init(smallCamel: String? = nil, capitalCamel: String? = nil, smallSnake: String? = nil, capitalSnake: String? = nil, sCAETHFlowPoints: String? = nil, ATT_NAME: String? = nil) {
+ self.smallCamel = smallCamel
+ self.capitalCamel = capitalCamel
+ self.smallSnake = smallSnake
+ self.capitalSnake = capitalSnake
+ self.sCAETHFlowPoints = sCAETHFlowPoints
+ self.ATT_NAME = ATT_NAME
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case smallCamel
+ case capitalCamel = "CapitalCamel"
+ case smallSnake = "small_Snake"
+ case capitalSnake = "Capital_Snake"
+ case sCAETHFlowPoints = "SCA_ETH_Flow_Points"
+ case ATT_NAME
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(smallCamel, forKey: .smallCamel)
+ try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel)
+ try container.encodeIfPresent(smallSnake, forKey: .smallSnake)
+ try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake)
+ try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints)
+ try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift
new file mode 100644
index 000000000000..253bbd7c04c6
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift
@@ -0,0 +1,40 @@
+//
+// Cat.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Cat: Codable, JSONEncodable, Hashable {
+
+ public var className: String
+ public var color: String? = "red"
+ public var declawed: Bool?
+
+ public init(className: String, color: String? = "red", declawed: Bool? = nil) {
+ self.className = className
+ self.color = color
+ self.declawed = declawed
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case className
+ case color
+ case declawed
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(className, forKey: .className)
+ try container.encodeIfPresent(color, forKey: .color)
+ try container.encodeIfPresent(declawed, forKey: .declawed)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift
new file mode 100644
index 000000000000..75b68ec01e27
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Category.swift
@@ -0,0 +1,36 @@
+//
+// Category.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Category: Codable, JSONEncodable, Hashable {
+
+ public var id: Int64?
+ public var name: String? = "default-name"
+
+ public init(id: Int64? = nil, name: String? = "default-name") {
+ self.id = id
+ self.name = name
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case id
+ case name
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(id, forKey: .id)
+ try container.encode(name, forKey: .name)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift
new file mode 100644
index 000000000000..a0419d54f15c
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift
@@ -0,0 +1,33 @@
+//
+// ClassModel.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+/** Model for testing model with \"_class\" property */
+public struct ClassModel: Codable, JSONEncodable, Hashable {
+
+ public var _class: String?
+
+ public init(_class: String? = nil) {
+ self._class = _class
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case _class
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(_class, forKey: ._class)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift
new file mode 100644
index 000000000000..21a539ba0109
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Client.swift
@@ -0,0 +1,32 @@
+//
+// Client.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Client: Codable, JSONEncodable, Hashable {
+
+ public var client: String?
+
+ public init(client: String? = nil) {
+ self.client = client
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case client
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(client, forKey: .client)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift
new file mode 100644
index 000000000000..dc3bb465a5f1
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift
@@ -0,0 +1,40 @@
+//
+// Dog.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Dog: Codable, JSONEncodable, Hashable {
+
+ public var className: String
+ public var color: String? = "red"
+ public var breed: String?
+
+ public init(className: String, color: String? = "red", breed: String? = nil) {
+ self.className = className
+ self.color = color
+ self.breed = breed
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case className
+ case color
+ case breed
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(className, forKey: .className)
+ try container.encodeIfPresent(color, forKey: .color)
+ try container.encodeIfPresent(breed, forKey: .breed)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift
new file mode 100644
index 000000000000..e06009060c54
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift
@@ -0,0 +1,44 @@
+//
+// EnumArrays.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct EnumArrays: Codable, JSONEncodable, Hashable {
+
+ public enum JustSymbol: String, Codable, CaseIterable {
+ case greaterThanOrEqualTo = ">="
+ case dollar = "$"
+ }
+ public enum ArrayEnum: String, Codable, CaseIterable {
+ case fish = "fish"
+ case crab = "crab"
+ }
+ public var justSymbol: JustSymbol?
+ public var arrayEnum: [ArrayEnum]?
+
+ public init(justSymbol: JustSymbol? = nil, arrayEnum: [ArrayEnum]? = nil) {
+ self.justSymbol = justSymbol
+ self.arrayEnum = arrayEnum
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case justSymbol = "just_symbol"
+ case arrayEnum = "array_enum"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(justSymbol, forKey: .justSymbol)
+ try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift
new file mode 100644
index 000000000000..6ea2895aee53
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift
@@ -0,0 +1,17 @@
+//
+// EnumClass.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public enum EnumClass: String, Codable, CaseIterable {
+ case abc = "_abc"
+ case efg = "-efg"
+ case xyz = "(xyz)"
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift
new file mode 100644
index 000000000000..3a9edb08ea78
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift
@@ -0,0 +1,66 @@
+//
+// EnumTest.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct EnumTest: Codable, JSONEncodable, Hashable {
+
+ public enum EnumString: String, Codable, CaseIterable {
+ case upper = "UPPER"
+ case lower = "lower"
+ case empty = ""
+ }
+ public enum EnumStringRequired: String, Codable, CaseIterable {
+ case upper = "UPPER"
+ case lower = "lower"
+ case empty = ""
+ }
+ public enum EnumInteger: Int, Codable, CaseIterable {
+ case _1 = 1
+ case number1 = -1
+ }
+ public enum EnumNumber: Double, Codable, CaseIterable {
+ case _11 = 1.1
+ case number12 = -1.2
+ }
+ public var enumString: EnumString?
+ public var enumStringRequired: EnumStringRequired
+ public var enumInteger: EnumInteger?
+ public var enumNumber: EnumNumber?
+ public var outerEnum: OuterEnum?
+
+ public init(enumString: EnumString? = nil, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger? = nil, enumNumber: EnumNumber? = nil, outerEnum: OuterEnum? = nil) {
+ self.enumString = enumString
+ self.enumStringRequired = enumStringRequired
+ self.enumInteger = enumInteger
+ self.enumNumber = enumNumber
+ self.outerEnum = outerEnum
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case enumString = "enum_string"
+ case enumStringRequired = "enum_string_required"
+ case enumInteger = "enum_integer"
+ case enumNumber = "enum_number"
+ case outerEnum
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(enumString, forKey: .enumString)
+ try container.encode(enumStringRequired, forKey: .enumStringRequired)
+ try container.encodeIfPresent(enumInteger, forKey: .enumInteger)
+ try container.encodeIfPresent(enumNumber, forKey: .enumNumber)
+ try container.encodeIfPresent(outerEnum, forKey: .outerEnum)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift
new file mode 100644
index 000000000000..1378b4f9b207
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/File.swift
@@ -0,0 +1,34 @@
+//
+// File.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+/** Must be named `File` for test. */
+public struct File: Codable, JSONEncodable, Hashable {
+
+ /** Test capitalization */
+ public var sourceURI: String?
+
+ public init(sourceURI: String? = nil) {
+ self.sourceURI = sourceURI
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case sourceURI
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(sourceURI, forKey: .sourceURI)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift
new file mode 100644
index 000000000000..f9a39d2e58e0
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift
@@ -0,0 +1,36 @@
+//
+// FileSchemaTestClass.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct FileSchemaTestClass: Codable, JSONEncodable, Hashable {
+
+ public var file: File?
+ public var files: [File]?
+
+ public init(file: File? = nil, files: [File]? = nil) {
+ self.file = file
+ self.files = files
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case file
+ case files
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(file, forKey: .file)
+ try container.encodeIfPresent(files, forKey: .files)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift
new file mode 100644
index 000000000000..1d15c6b37743
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift
@@ -0,0 +1,87 @@
+//
+// FormatTest.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct FormatTest: Codable, JSONEncodable, Hashable {
+
+ static let integerRule = NumericRule(minimum: 10, exclusiveMinimum: false, maximum: 100, exclusiveMaximum: false, multipleOf: nil)
+ static let int32Rule = NumericRule(minimum: 20, exclusiveMinimum: false, maximum: 200, exclusiveMaximum: false, multipleOf: nil)
+ static let numberRule = NumericRule(minimum: 32.1, exclusiveMinimum: false, maximum: 543.2, exclusiveMaximum: false, multipleOf: nil)
+ static let floatRule = NumericRule(minimum: 54.3, exclusiveMinimum: false, maximum: 987.6, exclusiveMaximum: false, multipleOf: nil)
+ static let doubleRule = NumericRule(minimum: 67.8, exclusiveMinimum: false, maximum: 123.4, exclusiveMaximum: false, multipleOf: nil)
+ static let stringRule = StringRule(minLength: nil, maxLength: nil, pattern: "/[a-z]/i")
+ static let passwordRule = StringRule(minLength: 10, maxLength: 64, pattern: nil)
+ public var integer: Int?
+ public var int32: Int?
+ public var int64: Int64?
+ public var number: Double
+ public var float: Float?
+ public var double: Double?
+ public var string: String?
+ public var byte: Data
+ public var binary: URL?
+ public var date: OpenAPIDateWithoutTime
+ public var dateTime: Date?
+ public var uuid: UUID?
+ public var password: String
+
+ public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: OpenAPIDateWithoutTime, dateTime: Date? = nil, uuid: UUID? = nil, password: String) {
+ self.integer = integer
+ self.int32 = int32
+ self.int64 = int64
+ self.number = number
+ self.float = float
+ self.double = double
+ self.string = string
+ self.byte = byte
+ self.binary = binary
+ self.date = date
+ self.dateTime = dateTime
+ self.uuid = uuid
+ self.password = password
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case integer
+ case int32
+ case int64
+ case number
+ case float
+ case double
+ case string
+ case byte
+ case binary
+ case date
+ case dateTime
+ case uuid
+ case password
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(integer, forKey: .integer)
+ try container.encodeIfPresent(int32, forKey: .int32)
+ try container.encodeIfPresent(int64, forKey: .int64)
+ try container.encode(number, forKey: .number)
+ try container.encodeIfPresent(float, forKey: .float)
+ try container.encodeIfPresent(double, forKey: .double)
+ try container.encodeIfPresent(string, forKey: .string)
+ try container.encode(byte, forKey: .byte)
+ try container.encodeIfPresent(binary, forKey: .binary)
+ try container.encode(date, forKey: .date)
+ try container.encodeIfPresent(dateTime, forKey: .dateTime)
+ try container.encodeIfPresent(uuid, forKey: .uuid)
+ try container.encode(password, forKey: .password)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift
new file mode 100644
index 000000000000..9e2fe8cc87fd
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift
@@ -0,0 +1,36 @@
+//
+// HasOnlyReadOnly.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct HasOnlyReadOnly: Codable, JSONEncodable, Hashable {
+
+ public var bar: String?
+ public var foo: String?
+
+ public init(bar: String? = nil, foo: String? = nil) {
+ self.bar = bar
+ self.foo = foo
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case bar
+ case foo
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(bar, forKey: .bar)
+ try container.encodeIfPresent(foo, forKey: .foo)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift
new file mode 100644
index 000000000000..b9a06034e01e
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/List.swift
@@ -0,0 +1,32 @@
+//
+// List.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct List: Codable, JSONEncodable, Hashable {
+
+ public var _123list: String?
+
+ public init(_123list: String? = nil) {
+ self._123list = _123list
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case _123list = "123-list"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(_123list, forKey: ._123list)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift
new file mode 100644
index 000000000000..c4792800425f
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift
@@ -0,0 +1,48 @@
+//
+// MapTest.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct MapTest: Codable, JSONEncodable, Hashable {
+
+ public enum MapOfEnumString: String, Codable, CaseIterable {
+ case upper = "UPPER"
+ case lower = "lower"
+ }
+ public var mapMapOfString: [String: [String: String]]?
+ public var mapOfEnumString: [String: String]?
+ public var directMap: [String: Bool]?
+ public var indirectMap: StringBooleanMap?
+
+ public init(mapMapOfString: [String: [String: String]]? = nil, mapOfEnumString: [String: String]? = nil, directMap: [String: Bool]? = nil, indirectMap: StringBooleanMap? = nil) {
+ self.mapMapOfString = mapMapOfString
+ self.mapOfEnumString = mapOfEnumString
+ self.directMap = directMap
+ self.indirectMap = indirectMap
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case mapMapOfString = "map_map_of_string"
+ case mapOfEnumString = "map_of_enum_string"
+ case directMap = "direct_map"
+ case indirectMap = "indirect_map"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString)
+ try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString)
+ try container.encodeIfPresent(directMap, forKey: .directMap)
+ try container.encodeIfPresent(indirectMap, forKey: .indirectMap)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift
new file mode 100644
index 000000000000..c15921ae6c76
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift
@@ -0,0 +1,40 @@
+//
+// MixedPropertiesAndAdditionalPropertiesClass.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, JSONEncodable, Hashable {
+
+ public var uuid: UUID?
+ public var dateTime: Date?
+ public var map: [String: Animal]?
+
+ public init(uuid: UUID? = nil, dateTime: Date? = nil, map: [String: Animal]? = nil) {
+ self.uuid = uuid
+ self.dateTime = dateTime
+ self.map = map
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case uuid
+ case dateTime
+ case map
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(uuid, forKey: .uuid)
+ try container.encodeIfPresent(dateTime, forKey: .dateTime)
+ try container.encodeIfPresent(map, forKey: .map)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift
new file mode 100644
index 000000000000..d5ab7e422f2b
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift
@@ -0,0 +1,37 @@
+//
+// Model200Response.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+/** Model for testing model name starting with number */
+public struct Model200Response: Codable, JSONEncodable, Hashable {
+
+ public var name: Int?
+ public var _class: String?
+
+ public init(name: Int? = nil, _class: String? = nil) {
+ self.name = name
+ self._class = _class
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case name
+ case _class = "class"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(name, forKey: .name)
+ try container.encodeIfPresent(_class, forKey: ._class)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift
new file mode 100644
index 000000000000..e8a19ee3d99b
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Name.swift
@@ -0,0 +1,48 @@
+//
+// Name.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+/** Model for testing model name same as property name */
+public struct Name: Codable, JSONEncodable, Hashable {
+
+ public var name: Int
+ public var snakeCase: NullEncodable = .encodeValue(11033)
+ public var property: String?
+ public var _123number: Int?
+
+ public init(name: Int, snakeCase: NullEncodable = .encodeValue(11033), property: String? = nil, _123number: Int? = nil) {
+ self.name = name
+ self.snakeCase = snakeCase
+ self.property = property
+ self._123number = _123number
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case name
+ case snakeCase = "snake_case"
+ case property
+ case _123number = "123Number"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(name, forKey: .name)
+ switch snakeCase {
+ case .encodeNothing: break
+ case .encodeNull, .encodeValue: try container.encode(snakeCase, forKey: .snakeCase)
+ }
+ try container.encodeIfPresent(property, forKey: .property)
+ try container.encodeIfPresent(_123number, forKey: ._123number)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift
new file mode 100644
index 000000000000..10fd059c8566
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift
@@ -0,0 +1,32 @@
+//
+// NumberOnly.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct NumberOnly: Codable, JSONEncodable, Hashable {
+
+ public var justNumber: Double?
+
+ public init(justNumber: Double? = nil) {
+ self.justNumber = justNumber
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case justNumber = "JustNumber"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(justNumber, forKey: .justNumber)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift
new file mode 100644
index 000000000000..bf7da6a3f862
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Order.swift
@@ -0,0 +1,58 @@
+//
+// Order.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Order: Codable, JSONEncodable, Hashable {
+
+ public enum Status: String, Codable, CaseIterable {
+ case placed = "placed"
+ case approved = "approved"
+ case delivered = "delivered"
+ }
+ public var id: Int64?
+ public var petId: Int64?
+ public var quantity: Int?
+ public var shipDate: Date?
+ /** Order Status */
+ public var status: Status?
+ public var complete: Bool? = false
+
+ public init(id: Int64? = nil, petId: Int64? = nil, quantity: Int? = nil, shipDate: Date? = nil, status: Status? = nil, complete: Bool? = false) {
+ self.id = id
+ self.petId = petId
+ self.quantity = quantity
+ self.shipDate = shipDate
+ self.status = status
+ self.complete = complete
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case id
+ case petId
+ case quantity
+ case shipDate
+ case status
+ case complete
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(id, forKey: .id)
+ try container.encodeIfPresent(petId, forKey: .petId)
+ try container.encodeIfPresent(quantity, forKey: .quantity)
+ try container.encodeIfPresent(shipDate, forKey: .shipDate)
+ try container.encodeIfPresent(status, forKey: .status)
+ try container.encodeIfPresent(complete, forKey: .complete)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift
new file mode 100644
index 000000000000..99568c8facf1
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift
@@ -0,0 +1,40 @@
+//
+// OuterComposite.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct OuterComposite: Codable, JSONEncodable, Hashable {
+
+ public var myNumber: Double?
+ public var myString: String?
+ public var myBoolean: Bool?
+
+ public init(myNumber: Double? = nil, myString: String? = nil, myBoolean: Bool? = nil) {
+ self.myNumber = myNumber
+ self.myString = myString
+ self.myBoolean = myBoolean
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case myNumber = "my_number"
+ case myString = "my_string"
+ case myBoolean = "my_boolean"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(myNumber, forKey: .myNumber)
+ try container.encodeIfPresent(myString, forKey: .myString)
+ try container.encodeIfPresent(myBoolean, forKey: .myBoolean)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift
new file mode 100644
index 000000000000..76c34b3c2ce6
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift
@@ -0,0 +1,17 @@
+//
+// OuterEnum.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public enum OuterEnum: String, Codable, CaseIterable {
+ case placed = "placed"
+ case approved = "approved"
+ case delivered = "delivered"
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift
new file mode 100644
index 000000000000..f93b402b0fd5
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift
@@ -0,0 +1,61 @@
+//
+// Pet.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Pet: Codable, JSONEncodable, Hashable {
+
+ public enum Status: String, Codable, CaseIterable {
+ case available = "available"
+ case pending = "pending"
+ case sold = "sold"
+ }
+ public var id: Int64?
+ public var category: Category?
+ public var name: String
+ public var photoUrls: [String]
+ public var tags: [Tag]?
+ /** pet status in the store */
+ public var status: NullEncodable
+
+ public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: [String], tags: [Tag]? = nil, status: NullEncodable = .encodeNull) {
+ self.id = id
+ self.category = category
+ self.name = name
+ self.photoUrls = photoUrls
+ self.tags = tags
+ self.status = status
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case id
+ case category
+ case name
+ case photoUrls
+ case tags
+ case status
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(id, forKey: .id)
+ try container.encodeIfPresent(category, forKey: .category)
+ try container.encode(name, forKey: .name)
+ try container.encode(photoUrls, forKey: .photoUrls)
+ try container.encodeIfPresent(tags, forKey: .tags)
+ switch status {
+ case .encodeNothing: break
+ case .encodeNull, .encodeValue: try container.encode(status, forKey: .status)
+ }
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift
new file mode 100644
index 000000000000..05cf40bedd38
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift
@@ -0,0 +1,36 @@
+//
+// ReadOnlyFirst.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct ReadOnlyFirst: Codable, JSONEncodable, Hashable {
+
+ public var bar: String?
+ public var baz: String?
+
+ public init(bar: String? = nil, baz: String? = nil) {
+ self.bar = bar
+ self.baz = baz
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case bar
+ case baz
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(bar, forKey: .bar)
+ try container.encodeIfPresent(baz, forKey: .baz)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift
new file mode 100644
index 000000000000..9429b341fa9b
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Return.swift
@@ -0,0 +1,33 @@
+//
+// Return.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+/** Model for testing reserved words */
+public struct Return: Codable, JSONEncodable, Hashable {
+
+ public var _return: Int?
+
+ public init(_return: Int? = nil) {
+ self._return = _return
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case _return = "return"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(_return, forKey: ._return)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift
new file mode 100644
index 000000000000..543f1fa5ad4a
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift
@@ -0,0 +1,32 @@
+//
+// SpecialModelName.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct SpecialModelName: Codable, JSONEncodable, Hashable {
+
+ public var specialPropertyName: Int64?
+
+ public init(specialPropertyName: Int64? = nil) {
+ self.specialPropertyName = specialPropertyName
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case specialPropertyName = "$special[property.name]"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift
new file mode 100644
index 000000000000..548b82c049e2
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift
@@ -0,0 +1,52 @@
+//
+// StringBooleanMap.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct StringBooleanMap: Codable, JSONEncodable, Hashable {
+
+
+ public enum CodingKeys: CodingKey, CaseIterable {
+ }
+
+ public var additionalProperties: [String: Bool] = [:]
+
+ public subscript(key: String) -> Bool? {
+ get {
+ if let value = additionalProperties[key] {
+ return value
+ }
+ return nil
+ }
+
+ set {
+ additionalProperties[key] = newValue
+ }
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ var additionalPropertiesContainer = encoder.container(keyedBy: String.self)
+ try additionalPropertiesContainer.encodeMap(additionalProperties)
+ }
+
+ // Decodable protocol methods
+
+ public init(from decoder: Decoder) throws {
+ let container = try decoder.container(keyedBy: CodingKeys.self)
+
+ var nonAdditionalPropertyKeys = Set()
+ let additionalPropertiesContainer = try decoder.container(keyedBy: String.self)
+ additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift
new file mode 100644
index 000000000000..f2dea74b09d8
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift
@@ -0,0 +1,36 @@
+//
+// Tag.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct Tag: Codable, JSONEncodable, Hashable {
+
+ public var id: Int64?
+ public var name: String?
+
+ public init(id: Int64? = nil, name: String? = nil) {
+ self.id = id
+ self.name = name
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case id
+ case name
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(id, forKey: .id)
+ try container.encodeIfPresent(name, forKey: .name)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift
new file mode 100644
index 000000000000..9a7d7e6c8e6a
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift
@@ -0,0 +1,48 @@
+//
+// TypeHolderDefault.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct TypeHolderDefault: Codable, JSONEncodable, Hashable {
+
+ public var stringItem: String = "what"
+ public var numberItem: Double
+ public var integerItem: Int
+ public var boolItem: Bool = true
+ public var arrayItem: [Int]
+
+ public init(stringItem: String = "what", numberItem: Double, integerItem: Int, boolItem: Bool = true, arrayItem: [Int]) {
+ self.stringItem = stringItem
+ self.numberItem = numberItem
+ self.integerItem = integerItem
+ self.boolItem = boolItem
+ self.arrayItem = arrayItem
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case stringItem = "string_item"
+ case numberItem = "number_item"
+ case integerItem = "integer_item"
+ case boolItem = "bool_item"
+ case arrayItem = "array_item"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(stringItem, forKey: .stringItem)
+ try container.encode(numberItem, forKey: .numberItem)
+ try container.encode(integerItem, forKey: .integerItem)
+ try container.encode(boolItem, forKey: .boolItem)
+ try container.encode(arrayItem, forKey: .arrayItem)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift
new file mode 100644
index 000000000000..dd67ca7851d4
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift
@@ -0,0 +1,48 @@
+//
+// TypeHolderExample.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct TypeHolderExample: Codable, JSONEncodable, Hashable {
+
+ public var stringItem: String
+ public var numberItem: Double
+ public var integerItem: Int
+ public var boolItem: Bool
+ public var arrayItem: [Int]
+
+ public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) {
+ self.stringItem = stringItem
+ self.numberItem = numberItem
+ self.integerItem = integerItem
+ self.boolItem = boolItem
+ self.arrayItem = arrayItem
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case stringItem = "string_item"
+ case numberItem = "number_item"
+ case integerItem = "integer_item"
+ case boolItem = "bool_item"
+ case arrayItem = "array_item"
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(stringItem, forKey: .stringItem)
+ try container.encode(numberItem, forKey: .numberItem)
+ try container.encode(integerItem, forKey: .integerItem)
+ try container.encode(boolItem, forKey: .boolItem)
+ try container.encode(arrayItem, forKey: .arrayItem)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift
new file mode 100644
index 000000000000..e55b50dc4f73
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models/User.swift
@@ -0,0 +1,61 @@
+//
+// User.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+#if canImport(AnyCodable)
+import AnyCodable
+#endif
+
+public struct User: Codable, JSONEncodable, Hashable {
+
+ public var id: Int64?
+ public var username: String?
+ public var firstName: String?
+ public var lastName: String?
+ public var email: String?
+ public var password: String?
+ public var phone: String?
+ /** User Status */
+ public var userStatus: Int?
+
+ public init(id: Int64? = nil, username: String? = nil, firstName: String? = nil, lastName: String? = nil, email: String? = nil, password: String? = nil, phone: String? = nil, userStatus: Int? = nil) {
+ self.id = id
+ self.username = username
+ self.firstName = firstName
+ self.lastName = lastName
+ self.email = email
+ self.password = password
+ self.phone = phone
+ self.userStatus = userStatus
+ }
+
+ public enum CodingKeys: String, CodingKey, CaseIterable {
+ case id
+ case username
+ case firstName
+ case lastName
+ case email
+ case password
+ case phone
+ case userStatus
+ }
+
+ // Encodable protocol methods
+
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encodeIfPresent(id, forKey: .id)
+ try container.encodeIfPresent(username, forKey: .username)
+ try container.encodeIfPresent(firstName, forKey: .firstName)
+ try container.encodeIfPresent(lastName, forKey: .lastName)
+ try container.encodeIfPresent(email, forKey: .email)
+ try container.encodeIfPresent(password, forKey: .password)
+ try container.encodeIfPresent(phone, forKey: .phone)
+ try container.encodeIfPresent(userStatus, forKey: .userStatus)
+ }
+}
+
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift
new file mode 100644
index 000000000000..57f3ecca3726
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift
@@ -0,0 +1,98 @@
+// OpenAPIDateWithoutTime.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+/// Represents a date without time information (e.g. a birthday) for transmission from and to a REST API
+///
+/// This type is used as a representation for openapi specs `date` format which does not contain
+/// time information as opposed to the `date-time` format. Although it internally uses `Date` for
+/// (de-)serialization as well the generator needs to be able to distinguish between the two formats.
+/// - note: As `Date` is agnostic to timezones (and calendars), timezone information is needed to be able to add
+/// an appropriate padding in order to transform to GMT+0 which is the assumed timezone in ISO 8601.
+/// When decoding, GMT+0 can be assumed (again: ISO8601) so there is no padding necessary and wrappedDate
+/// can be used safely.
+public struct OpenAPIDateWithoutTime: Codable, Hashable, Equatable {
+ public let wrappedDate: Date
+ public let timezone: TimeZone
+
+ public enum CodingKeys: CodingKey, CaseIterable {
+ case wrappedDate
+ case timezone
+ }
+
+ public enum DecodingError: Error {
+ case notADateString
+ }
+
+ /// On decoding ISO8601 timezone is assumed
+ public init(from decoder: Decoder) throws {
+ let container = try decoder.singleValueContainer()
+
+ let dateString = try container.decode(String.self)
+ guard let date = OpenISO8601DateFormatter.withoutTime.date(from: dateString) else {
+ throw DecodingError.notADateString
+ }
+ self.wrappedDate = date
+
+ self.timezone = OpenISO8601DateFormatter.withoutTime.timeZone
+ }
+
+ /// Convenience Initializer which is useful when dealing with optionals a lot like e.g. in API mappers
+ public init?(wrappedDate: Date?, timezone: TimeZone = .current) {
+ guard let wrappedDate = wrappedDate else {
+ return nil
+ }
+
+ self.init(wrappedDate: wrappedDate, timezone: timezone)
+ }
+
+ /// Designated Initializer for `OpenAPIDateWithoutTime`
+ ///
+ /// Since usually `Date`s without time components - as e.g. birthdays - are created Calendar- and timezone-aware
+ // it is important to also provide a timezone so that the generator is able to normalize the supplied Date to ISO8601 (GMT+0)
+ public init(wrappedDate: Date, timezone: TimeZone) {
+ self.wrappedDate = wrappedDate
+ self.timezone = timezone
+ }
+
+ /// Only the wrappedDate is encoded normalized to GMT+0 with an offset derived from the supplied Timezone
+ public func encode(to encoder: Encoder) throws {
+ var container = encoder.singleValueContainer()
+ try container.encode(OpenISO8601DateFormatter.withoutTime.string(from: normalizedWrappedDate()))
+ }
+
+ /// Normalizes the wrappedDate to GMT+0 according to the supplied timezone
+ fileprivate func normalizedWrappedDate() -> Date {
+ return wrappedDate.addingTimeInterval(
+ Double(timezone.secondsFromGMT(for: wrappedDate)))
+ }
+
+ public static func == (lhs: Self, rhs: Self) -> Bool {
+ Calendar.current.compare(lhs.wrappedDate, to: rhs.wrappedDate, toGranularity: .day) == .orderedSame
+ }
+}
+
+extension OpenAPIDateWithoutTime: JSONEncodable {
+ func encodeToJSON() -> Any {
+ return OpenISO8601DateFormatter.withoutTime.string(from: self.normalizedWrappedDate())
+ }
+}
+
+extension OpenAPIDateWithoutTime: RawRepresentable {
+ public typealias RawValue = String
+ public init?(rawValue: String) {
+ if let date = OpenISO8601DateFormatter.withoutTime.date(from: rawValue) {
+ self.init(wrappedDate: date)
+ } else {
+ return nil
+ }
+ }
+
+ public var rawValue: String {
+ OpenISO8601DateFormatter.withoutTime.string(from: normalizedWrappedDate())
+ }
+}
\ No newline at end of file
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift
new file mode 100644
index 000000000000..8275bd0861a8
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift
@@ -0,0 +1,56 @@
+//
+// OpenISO8601DateFormatter.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+// https://stackoverflow.com/a/50281094/976628
+public class OpenISO8601DateFormatter: DateFormatter, @unchecked Sendable {
+ static let withoutSeconds: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.calendar = Calendar(identifier: .iso8601)
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
+ formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
+ return formatter
+ }()
+
+ static let withoutTime: DateFormatter = {
+ let formatter = DateFormatter()
+ formatter.calendar = Calendar(identifier: .iso8601)
+ formatter.locale = Locale(identifier: "en_US_POSIX")
+ formatter.timeZone = TimeZone(secondsFromGMT: 0)
+ formatter.dateFormat = "yyyy-MM-dd"
+ return formatter
+ }()
+
+ private func setup() {
+ calendar = Calendar(identifier: .iso8601)
+ locale = Locale(identifier: "en_US_POSIX")
+ timeZone = TimeZone(secondsFromGMT: 0)
+ dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
+ }
+
+ override init() {
+ super.init()
+ setup()
+ }
+
+ required init?(coder aDecoder: NSCoder) {
+ super.init(coder: aDecoder)
+ setup()
+ }
+
+ override public func date(from string: String) -> Date? {
+ if let result = super.date(from: string) {
+ return result
+ } else if let result = OpenISO8601DateFormatter.withoutSeconds.date(from: string) {
+ return result
+ }
+
+ return OpenISO8601DateFormatter.withoutTime.date(from: string)
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift
new file mode 100644
index 000000000000..acf7ff4031bd
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift
@@ -0,0 +1,36 @@
+// SynchronizedDictionary.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+internal struct SynchronizedDictionary {
+
+ private var dictionary = [K: V]()
+ private let queue = DispatchQueue(
+ label: "SynchronizedDictionary",
+ qos: DispatchQoS.userInitiated,
+ attributes: [DispatchQueue.Attributes.concurrent],
+ autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit,
+ target: nil
+ )
+
+ internal subscript(key: K) -> V? {
+ get {
+ var value: V?
+
+ queue.sync {
+ value = self.dictionary[key]
+ }
+
+ return value
+ }
+ set {
+ queue.sync(flags: DispatchWorkItemFlags.barrier) {
+ self.dictionary[key] = newValue
+ }
+ }
+ }
+}
diff --git a/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Validation.swift b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Validation.swift
new file mode 100644
index 000000000000..b17dc24c155e
--- /dev/null
+++ b/samples/client/petstore/swift6/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Validation.swift
@@ -0,0 +1,161 @@
+// Validation.swift
+//
+// Generated by openapi-generator
+// https://openapi-generator.tech
+//
+
+import Foundation
+
+public struct StringRule: @unchecked Sendable {
+ public var minLength: Int?
+ public var maxLength: Int?
+ public var pattern: String?
+}
+
+public struct NumericRule: @unchecked Sendable {
+ public var minimum: T?
+ public var exclusiveMinimum = false
+ public var maximum: T?
+ public var exclusiveMaximum = false
+ public var multipleOf: T?
+}
+
+public struct ArrayRule: @unchecked Sendable {
+ public var minItems: Int?
+ public var maxItems: Int?
+ public var uniqueItems: Bool
+}
+
+public enum StringValidationErrorKind: Error {
+ case minLength, maxLength, pattern
+}
+
+public enum NumericValidationErrorKind: Error {
+ case minimum, maximum, multipleOf
+}
+
+public enum ArrayValidationErrorKind: Error {
+ case minItems, maxItems, uniqueItems
+}
+
+public struct ValidationError: Error {
+ public fileprivate(set) var kinds: Set
+}
+
+public struct Validator {
+ /// Validate a string against a rule.
+ /// - Parameter string: The String you wish to validate.
+ /// - Parameter rule: The StringRule you wish to use for validation.
+ /// - Returns: A validated string.
+ /// - Throws: `ValidationError` if the string is invalid against the rule,
+ /// `NSError` if the rule.pattern is invalid.
+ public static func validate(_ string: String, against rule: StringRule) throws -> String {
+ var error = ValidationError