如何解析“用于条件绑定的初始化器必须具有可选类型,而不是'Int'"? [英] How to resolve "Initializer for conditional binding must have Optional type, not 'Int'"?

查看:68
本文介绍了如何解析“用于条件绑定的初始化器必须具有可选类型,而不是'Int'"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了如何解决此错误的示例,但在我的情况下我无法使其正常工作.

I've seen examples of how to resolve this error but I can't get it to work in my case.

用于条件绑定的Initializer必须具有Optional类型,而不是'Int'

Initializer for conditional binding must have Optional type, not 'Int'

employeeCount 是否应该是可选的,因为它会推断出右侧?

Shouldn't employeeCount be optional since it is inferring the right side?

static func getEmployeeCount() -> Int {
    if let employeeCount = UserDefaults.standard.integer(forKey: "employeeCount") {
        return employeeCount as! Int
    }
    return 0
}

推荐答案

问题是

The problem is UserDefaults.standard.integer return Int, not Int?. So you don't need to wrap it with if let.

可选是否无关紧要.

在您的情况下,只需 return UserDefaults.standard.integer(forKey:"employeeCount")

这篇关于如何解析“用于条件绑定的初始化器必须具有可选类型,而不是'Int'"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆