قالب وردپرس درنا توس
Home / IOS Development / Swift Tips: Local Structural Definitions

Swift Tips: Local Structural Definitions



While we were working on our re-implementation of Swift Talk backend in Swift, we stumbled across – or stumbled across? – A somewhat cloudy language function. Fortunately, it has proven to be useful, and you may find it useful too.

We use Swift's Codable feature to generate and analyze the JSON and XML strings needed for API requests. This technique is something we talk about in Swift Talk 115 (a public episode) and 116, where we implement a custom XML decoder.

Let's say we need to send the following XML to the server:


    Some UUID 
   ] Some Token 

Instead of generating this XML string by string interpolation, we create a coding structure that represents contents of XML:

  struct UpdateBillingInfo: Codable, RootElement {
was account_id: UUID
was token_id: String
static la rootElementName = "billing_info"
}

Then we use our custom XML encoder to convert a UpdateBillingInfo value to an XML string. The XML encoder can take care of all proper formatting and escape, no matter what data we need to send.

Often we do not need to use these structures elsewhere, we only need to use them in the feature that generates the request. Cluttering namespace with all of these types is an unwelcome side effect of this approach, even if we make them private or nest them in another structure.

As it happens we can define a structure even more locally: in the body of a function!

Here is a function that generates the request with the payload over, with the structure nicely tucked in its local scope:

  func updatePaymentMethod (for account: UUID, token: String) -> RemoteEndpoint <RecurlyResult > {
struct Update: Codable, RootElement {
was account_id: UUID
was token_id: String
static la rootElementName = "billing_info"
}
la url = ...
return RemoteEndpoint (xml: .put, url: url, value: Update (account_id: accountId, token_id: token))
}

In this way, we still have the benefit of using Codable the data serialization infrastructure without connecting the namespace with foreign types. It is also very clear that this type is an implementation feature of the function.

For more useful stumbling, subscribe to Swift Talk. 🤓


Source link