从'String?'隐式强制转换为任何表达式

58

我有这样的错误:"Expression implicitly coerced from String? to Any" 这是我的代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    FIRApp.configure()
    FIRAuth.auth()?.signIn(withEmail: "myemail@gmail.com", password: "mypassword", completion: { (user, error) in
        if (error != nil) {
            print(user?.email)
        }else {
            print(error?.localizedDescription)
        }
    })

    return true
}

这行代码存在错误。

print(user?.email)

print(error?.localizedDescription)
请帮助我。

2
你可以使用 user?.email as Any 来明确表示你想将其转换为 Any - onmyway133
1个回答

51

print函数需要一组Any参数。其中StringAny的一种。在这种情况下,Xcode告诉你它将可选字符串默认转换为Any对象(通过将String值转换为Optional(value))。

要避免此警告,您可以简单地使用默认值或解包String?

print(user?.email ?? "User instance is nil")
print(user!.email)

1
如果在第二行用户为nil会发生什么? - probrandono
2
应用程序肯定会崩溃。但在我解释了Optional之后,我认为这是隐含的。 - Luca D'Alberti
6
每次写代码时都要写这些东西,真是一份苦差事。如果不打印输出信息就会导致应用程序崩溃。为什么不能只在变量为空时打印“nil”,然后就好了呢? - Zaporozhchenko Oleksandr
1
@ZaporozhchenkoAleksandr 我完全同意你的观点,但我的回答范围是解释为什么会出现错误以及如何摆脱它。最好的方法是你自己去找到它。 - Luca D'Alberti
1
@LucaD'Alberti 当然可以。那只是对本地API的抱怨;) 感谢你所做的一切。 - Zaporozhchenko Oleksandr
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接