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)
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.
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,
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 ...
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With