Swift 在appDelegate中设置UItabaritem标记值

Swift 在appDelegate中设置UItabaritem标记值,swift,appdelegate,uitabbaritem,Swift,Appdelegate,Uitabbaritem,我在这个问题上做了大量的搜索,并在Objective-C中找到了许多答案来实现这一点。然而,我还没有找到Swift中的答案 我已尝试翻译Objective-C,并在didfishlaunchingwithoptions中执行以下代码: if let rootViewController = self.window?.rootViewController { print("root") if let tabBarController = rootViewController.tab

我在这个问题上做了大量的搜索,并在Objective-C中找到了许多答案来实现这一点。然而,我还没有找到Swift中的答案

我已尝试翻译Objective-C,并在
didfishlaunchingwithoptions
中执行以下代码:

if let rootViewController = self.window?.rootViewController {
    print("root")
    if let tabBarController = rootViewController.tabBarController {
        print("tab")
        let tabBarItem = tabBarController.tabBar.items![3]
        tabBarItem.badgeValue = "!"
    }
}

代码从不打印“tab”,所以我显然没有正确访问它。帮助?

假设您的根视图控制器实际上是选项卡栏控制器,您需要更改:

if let tabBarController = rootViewController.tabBarController {
致:

if let tabBarController = rootViewController as? UITabBarController {