Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/97.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Alamofire:具有额外属性的可编码对象_Ios_Swift_Alamofire_Codable - Fatal编程技术网

Ios Alamofire:具有额外属性的可编码对象

Ios Alamofire:具有额外属性的可编码对象,ios,swift,alamofire,codable,Ios,Swift,Alamofire,Codable,我有一个可编码的对象模型,我正在用Alamofire检索它。但是,我想在模型中添加额外的布尔变量,它不是服务器端模型的一部分,在iOS上可能吗 为了符合Codable协议,我需要将其添加到CodingKeys枚举中,但如果我这样做,它会尝试从不存在的服务器解析属性。您只需为属性指定一个默认值,该属性应仅存在于iOS应用程序的模型类中,然后从您的CodingKeyenum中省略该属性的名称,您的模型类/结构仍将符合Codable,而无需将该属性编码/解码到JSON中 你可以在下面找到一个例子 st

我有一个可编码的对象模型,我正在用Alamofire检索它。但是,我想在模型中添加额外的布尔变量,它不是服务器端模型的一部分,在iOS上可能吗


为了符合Codable协议,我需要将其添加到CodingKeys枚举中,但如果我这样做,它会尝试从不存在的服务器解析属性。

您只需为属性指定一个默认值,该属性应仅存在于iOS应用程序的模型类中,然后从您的
CodingKey
enum
中省略该属性的名称,您的模型类/结构仍将符合
Codable
,而无需将该属性编码/解码到JSON中

你可以在下面找到一个例子

struct Person: Decodable {
    let name:String
    let age:Int
    var cached = false //not part of the JSON

    enum CodingKeys:String,CodingKey {
        case name, age
    }
}

let json = """
{"name":"John",
"age":22}
"""

do {
    let person = try JSONDecoder().decode(Person.self,from: json.data(using: .utf8)!)
    print(person) // Person(name: "John", age: 22, cached: false)
} catch {
    print(error)
}

您可以简单地为只应存在于iOS应用程序模型类中的属性指定一个默认值,然后从您的
CodingKey
enum
中省略该属性的名称,您的模型类/结构仍将符合
Codable
,而无需将该属性编码/解码为JSON

你可以在下面找到一个例子

struct Person: Decodable {
    let name:String
    let age:Int
    var cached = false //not part of the JSON

    enum CodingKeys:String,CodingKey {
        case name, age
    }
}

let json = """
{"name":"John",
"age":22}
"""

do {
    let person = try JSONDecoder().decode(Person.self,from: json.data(using: .utf8)!)
    print(person) // Person(name: "John", age: 22, cached: false)
} catch {
    print(error)
}

添加一些关于您所做工作的代码。在这种情况下很容易帮到你。你想用这个额外的变量实现什么?您可以将其设置为可选,如果API响应中不存在,则它将始终为nil。对于任何其他内容,您都应该使用计算属性。添加一些关于您所做工作的代码。在这种情况下很容易帮到你。你想用这个额外的变量实现什么?您可以将其设置为可选,如果API响应中不存在,则它将始终为nil。对于任何其他内容,都应该使用计算属性。