Skip to content

Parsing URL array-formatted parameter #107

Answered by mbrandonw
mergesort asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @mergesort, the second argument of Field is a Conversion, which describes a way of transforming an input to an output and back into an input. It's similar to a parser, but it does not consume anything. It just transforms back-and-forth.

So you can create a custom conversion for turning a string into an array of URLs and back:

struct CommaSeparatedURLs: Conversion {
  func apply(_ input: Substring) throws -> [URL] {
    input.split(separator: ",").compactMap { URL(string: String($0)) }
  }
  func unapply(_ output: [URL]) throws -> Substring {
    output.map(\.absoluteString).joined(separator: ",")[...]
  }
}

And then you can use this with Field:

Field("links", CommaSeparatedURLs())

And …

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@mergesort
Comment options

Answer selected by mergesort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants