【问题标题】:iOS Swift Decodable: Error: Cannot invoke initializer for type with no argumentsiOS Swift 可解码:错误:无法为没有参数的类型调用初始化程序
【发布时间】:2018-11-30 04:29:21
【问题描述】:

我在初始化结构时遇到错误,请参阅下面的屏幕截图。调试后,我发现在结构中包含审查变量会出现问题。 我无法弄清楚我做错了什么。 谁能帮帮我?

发送

我正在复制代码以防万一您需要尝试一下

import UIKit

struct RootValue : Decodable {
    private enum CodingKeys : String, CodingKey {
        case success = "success"
        case content = "data"
        case errors = "errors"
    }
    let success: Bool
    let content : [ProfileValue]
    let errors: [String]
}

struct ProfileValue : Decodable {
    private enum CodingKeys : String, CodingKey {
        case id = "id"
        case name = "name"
        case review = "review" // including this gives error
    }

    var id: Int = 0
    var name: String = ""
    var review: ReviewValues // including this gives error
}

struct ReviewValues : Decodable{
    private enum CodingKeys : String, CodingKey {
        case place = "place"
    }

    var place: String = ""
}

class ViewController: UIViewController {

    var profileValue = ProfileValue()

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

【问题讨论】:

  • 我将您的代码扔到 Playground 中,并被要求使用 var profileValue = ProfileValue(id: 0, name: "", review: ReviewValues(place: ""))。要克服它,您必须提供自定义 init 函数,但 review 不是可选的,因此您必须为其提供一个值

标签: ios swift swift4 decodable


【解决方案1】:

您的ProfileValue 结构没有review 属性的默认值。这就是编译器不满意的原因,因为您试图创建 ProfileValue 的实例而不为所有非可选属性提供默认值。

附带说明,您的所有编码键枚举值都与属性名称匹配。如果名称相同,则无需包含编码键枚举。

【讨论】:

    【解决方案2】:

    评论没有默认值,你需要改变这个

    var profileValue = ProfileValue()
    

    var profileValue:ProfileValue?
    

    var review: ReviewValues?
    

    ProfileValue结构中提供init方法

    【讨论】:

    • 谢谢 我试过这个 var review:ReviewValues?它正在工作。
    【解决方案3】:

    在 ProfileValue 结构中添加一个 init:

    struct ProfileValue : Decodable {
      private enum CodingKeys : String, CodingKey {
        case id = "id"
        case name = "name"
        case review = "review" // including this gives error
      }
    
      var id: Int = 0
      var name: String = ""
      var review: ReviewValues // including this gives error
    
      init() {
        self.review = ReviewValues()
      }
    }
    

    【讨论】:

      【解决方案4】:

      添加默认的init方法,在可编码的modal中提供默认的init方法来创建编码对象。

      struct Modal: Codable {
      
          var status: String?
          var result : [Result?]?
      
          // To provide the default init method to create the encoded object
      
          init?() {
              return nil
          }
      
          private enum CodingKeys: String, CodingKey {
              case status = "status"
              case result = "result"
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-15
        相关资源
        最近更新 更多