我正在使用常量构建struct
以形成URL
个端点。
struct Constants {
struct Api {
static let BaseUrl = "http://srv.com/ws_rest/"
static let LoginPassword1 = "credentials?member_account_pwd="
static let LoginUsername2 = "&member_account_login="
static let Login3 = "&channelId=4"
}
}
最终结果是:
let url = URL.baseUrlWith(string: Constants.Api.LoginPassword1 + "pass" + Constants.Api.LoginUsername2 + "user" + Constants.Api.Login3)
这仅适用于一个端点。有没有人知道对此有更好的实际帮助?
答案 0 :(得分:1)
拥有一个可以帮助你的功能
可能很有用 func urlString(with baseURL: String, and parameters: [String: String])->String {
var mutableBaseURL = baseURL
for (i, param) in parameters.enumerated() {
var symbol = "&"
if i == 0 { symbol = "?" }
mutableBaseURL += "\(symbol)\(param.key)=\(param.value)"
}
return mutableBaseURL
}
所以你的常量会变成类似
的东西struct Constants {
struct Endpoints {
static let login = "http://srv.com/ws_rest/credentials"
}
struct Parameters {
static let username = "member_account_login"
static let password = "member_account_pwd"
static let channelId = "channelId"
}
}
您的代码中的某处
let url = urlString(with: Constants.Endpoints.login, and: [
Constants.Parameters.username: username,
Constants.Parameters.password: pass,
Constants.Parameters.channelId: "4"
])
希望它有所帮助。