通过 CustomStringConvertible 从 Struct 形成字符串

cas*_*las 0 ios swift

我正在尝试构建一个类似的 URL 查询

limit=20&offset=0

如果没有,limit则 URL 查询应如下所示

offset=0

我尝试按如下方式形成字符串,但我的结构项是可选的;因此,我很困惑想出一个字符串。

struct Filter {
  var limit: Int?
  var offset: Int?
}

extension Filter:CustomStringConvertible {
  var description: String {
    return "limit=\(limit)&offset=\(offset)"
  }
}
Run Code Online (Sandbox Code Playgroud)

Wit*_*ski 5

如果你真的想坚持使用 String 版本,这是我的看法:

extension Filter: CustomStringConvertible {
    var description: String {
        [
            limit.map { "limit=\($0)" },
            offset.map { "offset=\($0)" }
        ].compactMap { $0 }.joined(separator: "&")
    }
}
Run Code Online (Sandbox Code Playgroud)

但是由于已经有一些评论可以指导您找到好的解决方案,我想我可以为您提供一个示例。让我们从为Filter对象构建查询项开始。

extension Filter {
    var queryItems: [URLQueryItem] {
        var items = [URLQueryItem]()
        if let limit = limit {
            items.append(URLQueryItem(name: "limit", value: limit))
        }
        if let offset = offset {
            items.append(URLQueryItem(name: "offset", value: offset))
        }
        return items
    }
}
Run Code Online (Sandbox Code Playgroud)

现在使用它构建 URL 非常容易 URLComponents

let filter: Filter

var components = URLComponents()
components.scheme = "https" // example scheme
components.host = "api.github.com" // example url
components.path = "/search/repositories" // example path
components.queryItems = filter.queryItems

let url = components.url
Run Code Online (Sandbox Code Playgroud)

John Sundell 有一篇关于Constructing URLs in Swift的好文章