Going from Swift to Go: Parsable Structs

Going from Swift to Go: Parsable Structs

Structs are a basic element of object-oriented languages, and usually simple to implement. But when dealing with Swift and Go, one thing we frequently run into is parsing with json–that means creating a struct that can parse json data. How can we do this?

Basic Structs

In both Swift and Go, we start a struct with ‘struct’ followed by the struct name (reverse order in Go). In the following lines, between the brackets, we have a list of variables, declared differently in each language. In Swift, we declare the variables without setting them; for example, ‘let var: string!’. For structs in Swift, it is important to clarify if the variable can be nil, so the declaration should end with ‘!’ or ‘?’. In Go, we simply give the variable name followed by variable type — no extra characters.

Swift example:
struct structName {
var firstVariable: String!
}

Go example:
structName struct {
firstVariable String
}

Make Structs JSON Structs

To make Swift struct codable, after the struct name, we add ‘:’ followed by the type ‘Codable’. Done. In Go, for each variable we need to add a line defining the json key, in the form `json:”key”` , making sure to use the ` character.

Swift example:
struct structName: Codable {
var firstVariable: String!
}

Go example:
structName struct {
firstVariable String `json:"variableKey"`
}

But where do we set the variable key in Swift? Actually, the variable name is the variable key in Swift.

Use Struct to Parse JSON into a Variable

Now that we have an appropriate struct, how can we use it to turn json into something useful? In Go, we do ‘json.NewDecoder’ and pass the json data as a parameter; this creates a decoder that will decode the desired json. We then call ‘Decode’ and pass a variable that conforms to our struct (and put ‘&’ at the start of the variable). Don’t forget to import “encoding/json” to use the json library.

Example in Go:
receptorVariable := structName{}
json.NewDecoder(jsonData).Decode(&receptorVariable)

In Swift, it’s a bit more complicated, because we must use a do/catch block. Inside the ‘do’ section, create a new variable, and set it equal to ‘try JSONDecoder().decode’ and pass the struct followed by ‘.self’, and for the second parameter pass the json data.

Swift example:
do {
let receptorVariable = try JSONDecoder().decode(structName.self, from: jsonData)
} catch {
print("JSON parsing failed") //something to catch the failed JSON parsing
}