gpt4 book ai didi

swift - 从初始化器返回而不初始化所有存储的属性错误 - 但一切都已初始化

转载 作者:行者123 更新时间:2023-11-30 12:46:27 25 4
gpt4 key购买 nike

我遇到了这个奇怪的错误。它工作正常,直到我添加了 image 和 imageString 值,然后发生了这个错误:

Return from initializer without initializing all stored properties

我以为我初始化了所有属性,但不确定为什么会发生此错误。这是自定义对象类

class JSONObject {
private let baseImageURL = "https://website.com"

var airbnbUS: Int
var airbnbLocal: Int
var imageString: String
var image: URL

init(airbnbUS: Int, airbnbLocal: Int, imageString: String, image: URL ){

self.airbnbUS = airbnbUS
self.airbnbLocal = airbnbLocal
self.imageString = imageString
self.image = image
}

init(resultsDictionary:[String: Any]){
guard let cost = resultsDictionary["cost"] as? [String: Any],
let airbnb = cost["airbnb_median"] as? [String : Any],
let usd = airbnb["USD"] as? Int,
let chf = airbnb["CHF"] as? Int
else {
airbnbUS = 0
airbnbLocal = 0
return
}

airbnbUS = usd
airbnbLocal = chf

guard let media = (resultsDictionary["media"] as? [String: Any]),
let imageDictionary = media["image"] as? [String: Any],
let image1000 = imageDictionary["1000"] as? String
else {
imageString = ""
image = URL(string: "\(baseImageURL)")!
return
}
imageString = image1000
image = URL(string: "\(baseImageURL)\(imageString)")!
}
}

最佳答案

问题出在您的 resultsDictionary 中初始化程序。 return在你的第一个guard语句可以提前从初始化器返回,并且以下 guard语句(以及分配 imageimageString 属性的代码)可能无法执行。

一个解决方案是更改第一个 guard声明if-let声明。

init(resultsDictionary:[String: Any]){

if let cost = resultsDictionary["cost"] as? [String: Any],
let airbnb = cost["airbnb_median"] as? [String : Any],
let usd = airbnb["USD"] as? Int,
let chf = airbnb["CHF"] as? Int
{
airbnbUS = usd
airbnbLocal = chf
} else {
airbnbUS = 0
airbnbLocal = 0
}

guard let media = (resultsDictionary["media"] as? [String: Any]),
let imageDictionary = media["image"] as? [String: Any],
let image1000 = imageDictionary["1000"] as? String
else {
imageString = ""
image = URL(string: "\(baseImageURL)")!
return
}
imageString = image1000
image = URL(string: "\(baseImageURL)\(imageString)")!
}

关于swift - 从初始化器返回而不初始化所有存储的属性错误 - 但一切都已初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41581628/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com