mirror of
https://github.com/Moya/Moya.git
synced 2026-03-18 19:52:28 +00:00
65 lines
1.6 KiB
Markdown
65 lines
1.6 KiB
Markdown
# Optional request parameters
|
|
|
|
Suppose you want to call `api/users?limit=10` but also `api/users`:
|
|
|
|
```swift
|
|
public enum MyService {
|
|
case users(limit: Int?)
|
|
}
|
|
|
|
extension MyService: TargetType {
|
|
//...
|
|
public var task: Task {
|
|
switch self {
|
|
case .users(let limit):
|
|
var params: [String: Any] = [:]
|
|
params["limit"] = limit
|
|
return .requestParameters(parameters: params, encoding: URLEncoding.default)
|
|
default:
|
|
return .requestPlain
|
|
}
|
|
}
|
|
//...
|
|
}
|
|
```
|
|
|
|
In this case `params["limit"] = nil` will be equal of removing object for key `limit`.
|
|
|
|
This will work for any type of requests, since method type is defined in separate property
|
|
|
|
```swift
|
|
extension MyService: TargetType {
|
|
//...
|
|
public var method: Moya.Method {
|
|
switch self {
|
|
case .emailAuth:
|
|
return .post
|
|
default:
|
|
return .get
|
|
}
|
|
}
|
|
//...
|
|
}
|
|
```
|
|
|
|
## Important Note
|
|
|
|
You **have to** add optional parameters like shown above, one per line. Optional parameters won't be removed in case of ```nil``` if you try to initialize them within one line, e.g.:
|
|
|
|
```swift
|
|
//...
|
|
// This won't work!
|
|
public var parameters: [String: Any]? {
|
|
switch self {
|
|
case .users(let limit):
|
|
let params: [String: Any] = ["limit": limit]
|
|
return .requestParameters(parameters: params, encoding: URLEncoding.default)
|
|
default:
|
|
return .requestPlain
|
|
}
|
|
}
|
|
//...
|
|
```
|
|
|
|
In this case the URL request would contain a parameter like ```api/users?limit=nil``` if limit is ```nil```.
|