简体   繁体   中英

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)

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)

You cannot directly pass struct as parameter. You need to convert your struct into [String:Any] . I have added a new variable description that converts your content to 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 the usage is

var user = UserInfo(userId: 1, firstname: "John", lastname: "Skew")

// Convert user to Parameters for Alamofire
Alamofire.request("https://httpbin.org/post", parameters: user.description)

If you're going to make parameters to be sent as a POST request then it should take a dictionary format as follows:

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

This should work as "parameters" for your networking

在Swift 4中,您可以使用Decodable / Codable Struct

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM