Swift 3:如何将struct转换为Parameters

时间:2016-11-02 07:19:22

标签: ios swift serialization

我有一个struct如下

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

如何序列化UserInfo的实例以键入Parameters

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

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

5 个答案:

答案 0 :(得分:17)

只需实现dictionaryRepresentation计算变量或函数:

struct UserInfo {
    var userId : Int

    var firstName : String
    var lastName : String

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

用法:

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

答案 1 :(得分:4)

您可以使用CodableFirebase库。虽然它的主要用途是将其与Firebase Realtime DatabaseFirestore一起使用,但它实际上可以满足您的需求 - 将值转换为字典[String: Any]

您的模型将如下所示:

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

然后你会按照以下方式将它转换为字典:

import CodableFirebase

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

答案 2 :(得分:3)

您无法直接将struct作为参数传递。您需要将结构转换为[String:Any]。我添加了一个新的变量描述,将您的内容转换为字典

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]
        }
    }
}

用法是

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 :(得分:2)

如果您要将参数作为POST请求发送,那么它应采用如下的字典格式:

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

这应该作为网络的“参数”

答案 4 :(得分:2)

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