Chewie The Chorkie
Chewie The Chorkie

Reputation: 5234

Swift: Cannot convert value of type 'Int?' to specified type 'UInt32'

I'm trying to assign an array count to a UInt32. I get the error "Cannot convert value of type 'Int?' to specified type 'UInt32'". The array count is type Int, but the error says "Int?", which looks like an optional Int. I have no idea what else it could mean.

let randColorCount:UInt32 = slider?.randUIColors.count

I've also tried:

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

But I get the error "Cannot invoke initializer for type 'UInt32' with an argument list of type '(Int?)'".

Upvotes: 2

Views: 2425

Answers (1)

rmaddy
rmaddy

Reputation: 318824

slider?.randUIColors.count results in Int? because of the use of the optional chaining.

One simple solution is to combine this with the nil coalescing operator ?? to provide a default value incase slider is nil.

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

Upvotes: 6

Related Questions