Swift:无法转换“ Int”类型的值?到指定的类型'UInt32'

时间:2018-07-09 17:12:46

标签: swift optional uint32

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

let randColorCount:UInt32 = slider?.randUIColors.count

我也尝试过:

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

但是我收到错误消息“无法为类型为'(Int?)'的参数列表调用'UInt32'类型的初始化程序”。

1 个答案:

答案 0 :(得分:6)

slider?.randUIColors.count由于使用可选链接而产生Int?

一个简单的解决方案是将其与nil合并运算符??结合使用,以在slidernil的情况下提供默认值。

let randColorCount = UInt32(slider?.randUIColors.count ?? 0)
相关问题