代码之家  ›  专栏  ›  技术社区  ›  bcye

初始化器中的错误“初始化前使用的常量”self.apiKey

  •  1
  • bcye  · 技术社区  · 6 年前

    我有一个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
        }
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Sulthan    6 年前

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

    自从你 init 已失败,您可以返回 nil :

    } catch {
        print(error)
        return nil
    }
    
        2
  •  0
  •   Suhit Patil    6 年前

    您已经将apiKey定义为可选的,因此在初始化时它不能为零,请将其从let更改为var,它应该可以工作。或者从catch块返回nil来处理错误。

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