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 to serialize an instance of UserInfo to enter Parameters ?

 var user = UserInfo(userId: 1, firstName: "John", lastName: "Skew") // Convert user to Parameters for Alamofire Alamofire.request("https://httpbin.org/post", parameters: parameters) 
+8
ios serialization swift
source share
5 answers

Just implement a computed variable or dictionaryRepresentation function:

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

Using:

 var user = UserInfo(userId: 1, firstName: "John", lastName: "Skew") let userDict = user.dictionaryRepresentation 
+14
source share

You can use the CodableFirebase library. Although the main goal is to use it with the Firebase Realtime Database and Firestore , it really does what you need - it converts the value to the [String: Any] dictionary.

Your model will look like this:

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

And then you convert it to a dictionary as follows:

 import CodableFirebase let model: UserInfo // here you will create an instance of UserInfo let dict: [String: Any] = try! FirestoreEncoder().encode(model) 
+4
source share

You cannot pass struct directly as a parameter. You need to convert the structure to [String:Any] . I added a new variable description that converts your content into a dictionary

 struct UserInfo { var userId : Int var firstname : String var lastname : String var description:[String:Any] { get { return ["userId":userId, "firstname": self.firstname, "lastname": lastname] as [String : Any] } } } 

And use

 var user = UserInfo(userId: 1, firstname: "John", lastname: "Skew") // Convert user to Parameters for Alamofire Alamofire.request("https://httpbin.org/post", parameters: user.description) 
+3
source share

If you want the parameters to be sent as a POST request, then it should accept the dictionary format as follows:

 let userDict = ["userId" : user.userId, "firstname" : user.firstname, "lastname" : user.lastname] 

This should work as β€œparameters” for your network.

+2
source share

In Swift 4 you can use Decodable / Codable Struct

+1
source share

All Articles