Swift:无法将类型"Int?"的值转换为指定类型"UInt32"



我正在尝试将数组计数分配给UInt32。我收到错误"无法将类型'Int?'的值转换为指定类型'UInt32'"。数组计数的类型为 Int,但错误显示"Int?",这看起来像一个可选的 Int。我不知道它还意味着什么。

let randColorCount:UInt32 = slider?.randUIColors.count

我也试过:

let randColorCount:UInt32 = UInt32(slider?.randUIColors.count)

但是我收到错误"无法使用类型为'(Int?('的参数列表调用类型'UInt32'的初始值设定项"。

由于使用了可选链接,slider?.randUIColors.count导致Int?

一个简单的解决方案是将其与 nil 合并运算符相结合,??以提供默认值slider以防nil

let randColorCount = UInt32(slider?.randUIColors.count ?? 0)

最新更新