【问题标题】:Getting "guard body may not fall through" error when setting up Google Analytics on iOS Project (in Swift) [duplicate]在 iOS 项目(在 Swift 中)设置 Google Analytics 时出现“保护体可能无法通过”错误 [重复]
【发布时间】:2017-06-27 18:01:37
【问题描述】:

尝试在 XCode 上存档我的构建时出现以下错误:

/Users/AppDelegate.swift:18:9: 'guard' body 可能不会掉下来, 考虑使用 'return' 或 'break' 退出范围

这有点令人沮丧,因为它是 Google Analytics(我刚刚复制/粘贴)建议您放入 appdelegate 以设置其分析的确切代码。此外,它仅在归档我的构建时发生。仅在模拟器中运行我的代码时不会发生。

如果有人有一些想法,将不胜感激。

编辑:我也尝试在断言之后放置一个中断或继续,但我得到了一个错误......关于它不是一个循环的东西。

import UIKit
import Firebase

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FIRApp.configure()

        //Google Analytics
        guard let gai = GAI.sharedInstance() else {
            assert(false, "Google Analytics not configured correctly")
        }
        gai.tracker(withTrackingId: "xxxxxxxxxxx")
        // Optional: automatically report uncaught exceptions.
        gai.trackUncaughtExceptions = true

        // Optional: set Logger to VERBOSE for debug information.
        // Remove before app release.
        gai.logger.logLevel = .verbose;


        return true
    }

【问题讨论】:

  • 请参阅stackoverflow.com/a/29149643/1187415,了解为什么该错误仅发生在“存档”版本而不是“调试”版本中。
  • 您应该使用assertionFailure 而不是assert(false,...),但不幸的是,assertionFailure 不会返回 Never,这将满足保护语句退出作用域的要求。
  • @Alexander:与 fatalError() 相比,“-O”构建中也忽略了 assertionFailure。
  • @MartinR 很有趣。你能想出一个assertionFailure 更可取的用例吗?
  • 即使 Google Analytics 无法初始化,您也可能希望已发布的应用程序运行。

标签: ios swift xcode google-analytics


【解决方案1】:

guard let 函数需要退出 gai 变量的当前范围。所以你需要修改你的代码来

guard let gai = GAI.sharedInstance() else {
    assert(false, "Google Analytics not configured correctly")
    return true//Base on your function return type, it may be returning something else
}

这里是document

guard 语句的 else 子句是必需的,并且必须调用 用 noreturn 属性或传输程序标记的函数 使用其中之一控制守卫语句的封闭范围之外 以下陈述:

return break continue throw

【讨论】:

  • void 函数中出现意外的非 void 返回值
  • @AbhishekMitra 您只需要退出当前范围。返回类型取决于您的函数返回类型。如果您的函数没有返回任何内容,那么只需执行 return
猜你喜欢
  • 1970-01-01
  • 2020-06-26
  • 2016-05-04
  • 2020-10-14
  • 1970-01-01
  • 2015-06-08
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多