Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3 : How to convert struct to Parameters

I have a struct as follows

struct UserInfo
{
    var userId : Int
    var firstName : String
    var lastName : String
}

How do I serialize an instance of UserInfo to type Parameters?

var user = UserInfo(userId: 1, firstName: "John", lastName: "Skew")

// Convert user to Parameters for Alamofire
Alamofire.request("https://httpbin.org/post", parameters: parameters)
like image 485
Jaseem Abbas Avatar asked Nov 02 '16 07:11

Jaseem Abbas


People also ask

How do you define parameters in Swift?

Function parameters and return values are extremely flexible in Swift. You can define anything from a simple utility function with a single unnamed parameter to a complex function with expressive parameter names and different parameter options. Functions aren’t required to define input parameters.

How to define a function inside a swift struct?

We can also define a function inside a swift struct. A function defined inside a struct is called a method. In the above example, we have defined the method named applyBraking () inside the Car struct. Notice the accessing of the method,

How do you declare a function in Swift?

Swift Function Declaration 1 func - keyword used to declare a function 2 functionName - any name given to the function 3 parameters - any value passed to function 4 returnType - specifies the type of value returned by the function More ...

What is Swift’s unified function syntax?

Swift’s unified function syntax is flexible enough to express anything from a simple C-style function with no parameter names to a complex Objective-C-style method with names and argument labels for each parameter.


Video Answer


2 Answers

Just implement a dictionaryRepresentation computed variable or function:

struct UserInfo {
    var userId : Int

    var firstName : String
    var lastName : String

    var dictionaryRepresentation: [String: Any] {
        return [
            "userId" : userId,
            "firstName" : firstName,
            "lastName" : lastName
        ]
    }
}

Usage:

var user = UserInfo(userId: 1, firstName: "John", lastName: "Skew")
let userDict = user.dictionaryRepresentation
like image 50
alexburtnik Avatar answered Sep 27 '22 20:09

alexburtnik


You could use CodableFirebase library. Although it's main purpose is to use it with Firebase Realtime Database and Firestore, it actually does what you need - converts the value into dictionary [String: Any].

Your model would look the following:

struct UserInfo: Codable {
    var userId : Int
    var firstName : String
    var lastName : String
}

And then you would convert it to dictionary in the following way:

import CodableFirebase

let model: UserInfo // here you will create an instance of UserInfo
let dict: [String: Any] = try! FirestoreEncoder().encode(model)
like image 22
Noobass Avatar answered Sep 27 '22 22:09

Noobass