How to resolve “Initializer for conditional binding must have Optional type, not 'Int'”?

我是研究僧i 提交于 2019-12-30 14:46:10

问题


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

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

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
}

回答1:


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

The optional is irrelevant whether on right side.

In your case, just return UserDefaults.standard.integer(forKey: "employeeCount")



来源:https://stackoverflow.com/questions/48555028/how-to-resolve-initializer-for-conditional-binding-must-have-optional-type-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!