如何解决防护中的"Initializer for conditional binding must have Optional type, not 'Int'"错误?



我正在尝试使用 guard 初始化变量,但收到以下错误:

条件绑定的初始值设定项必须具有可选类型,而不是"Int">

这是我的代码:

guard let checkMarkPosition = UserDefaults.standard.integer(forKey: "showOnCustomButton") else {return}

我已经读过类似的保护错误:保护让错误:条件绑定的初始值设定项必须具有可选类型而不是"字符串">

但在这种情况下,代码被强制解开。就我而言,我不使用任何!.我尝试在这里和那里添加?以查看会发生什么,但我仍然收到相同的错误。

苹果文档说:

与指定键关联的整数值。如果指定的键不存在,则此方法返回 0。

方法integer(forKey:)返回Int,而不是Int?,所以这不是可选的,您不能在这里使用 guard。

integer(forKey返回不可选,默认值为0

let checkMarkPosition = UserDefaults.standard.integer(forKey: "showOnCustomButton")

相关内容

最新更新