gpt4 book ai didi

ios - 错误 "Constant ' self.apiKey' used before being initialized"in Initializer

转载 作者:行者123 更新时间:2023-11-28 06:00:07 25 4
gpt4 key购买 nike

我有一个 YoutubeAPIClient 类:

import Foundation

class YoutubeAPIClient {
let apiKey: String?

init?() {
do {
apiKey = try Environment().getValue(for: "YOUTUBE_API_KEY") as? String
} catch {
//TODO: Implement error handling
print(error)
}
}
}

在 init 方法中我试图初始化 apiKey 但它说:

Constant 'self.apiKey' used before being initialized

如果有帮助,我已经包含了环境代码结构:

import Foundation

struct Environment {

func getValue(for key: String) throws -> Any {

guard let value = ProcessInfo.processInfo.environment[key] else {
throw GenericError.noValueForKeyInEnvironment
}

return value
}
}

最佳答案

您必须处理错误,否则实例将以未定义状态结束(apiKey 在发生错误时未初始化)。

由于您的init 已经是可失败的,您可以只返回nil:

} catch {
print(error)
return nil
}

关于ios - 错误 "Constant ' self.apiKey' used before being initialized"in Initializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088118/

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