Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/106.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 Swift中具有子类的可解码_Ios_Swift_Codable_Decodable - Fatal编程技术网

Ios Swift中具有子类的可解码

Ios Swift中具有子类的可解码,ios,swift,codable,decodable,Ios,Swift,Codable,Decodable,我是swift中可解码的新手。我刚刚学会了如何使用它,但我一直在尝试解码另一个类的init中的子类(来自decoder:) 问题是如何从原始类init解码另一个类 我得到一个用户JSON文件,如下所示 { firstName:Tim, LastName: Apple, ... socialNetworks: [ { name: Facebook, username: Tim85,

我是swift中可解码的新手。我刚刚学会了如何使用它,但我一直在尝试解码另一个类的init中的子类(来自decoder:)

问题是如何从原始类init解码另一个类

我得到一个用户JSON文件,如下所示

{
     firstName:Tim,
     LastName: Apple,
     ...
     socialNetworks: [
         {
             name: Facebook,
             username: Tim85,
             ...
         },
         {
             name: Twitter,
             username: Tim_85,
             ...
         },
         ...
     ],
 }
我有一个像这样的用户类

class User: Codable {

   firstName: String,
   lastName: String,
   ...
   socialNetworks: [SocialNetwork]


   enum CodingKeys: String, CodingKey {
       case firstName, lastName, ..., socialNetworks
   }

   required init(from decoder: Decoder) throws {
       let container = try decoder.container(keyedBy: CodingKeys.self)

       self.firstName = try container.decodeIfPresent(String.self, forKey: .firstName) ?? ""
       self.lastName = try container.decodeIfPresent(String.self, forKey: .lastName) ?? ""

       // How do I also decode SocialNetworks???

   }

   ...

}
我还有一门社交网络课

class SocialNetwork: Codable {

   name: String,
   username: String,
   ...


   enum CodingKeys: String, CodingKey {
       case name, username, ...
   }

   required init(from decoder: Decoder) throws {
       let container = try decoder.container(keyedBy: CodingKeys.self)

       self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? ""
       self.username = try container.decodeIfPresent(String.self, forKey: .userName) ?? ""
   }

   ...

}

您不必编写任何自定义init

struct Root: Codable {
    let firstName, lastName: String
    let socialNetworks: [SocialNetwork]

    enum CodingKeys: String, CodingKey { // you can remove this block if LastName starts with l small instead of L
        case firstName
        case lastName = "LastName"
        case socialNetworks
    }
}

struct SocialNetwork: Codable {
    let name, username: String
}

试一试吧

self.socialNetworks = try container.decodeIfPresent([SocialNetwork].self, forKey: .socialNetworks) ?? []

但是解码器为您执行此操作

首先,它不是一个子类,其次,在我看来,您根本不需要实现
init(from:decoder)
,而是让swift自动为您处理此操作。您应该执行类似于
let result=try decoder.decode(User.self,from:data)
的操作,它应该可以工作。