I want to create a array with 4 null elements of type int. So I tried doing this it is not working.
var someInts:[Int] = [null, null, null,null]
I want to create a array with 4 null elements of type int. So I tried doing this it is not working.
var someInts:[Int] = [null, null, null,null]
An Int
can’t be nil
(nil
is Swift’s word for other languages’ null
), but an Optional can be nil
, and wrap any type. Like Int
, for example!
Two options:
var someInts = [Int?](repeating: nil, count: 4)
var someInts = Array(repeating: Int?.none, count: 4)
You can’t put nil (aka null in other languages) values into an array that takes Int values. That’s actually a feature of the Swift language. If you have an array of Ints, then you know that every value in that array is non-null and can safely be used.
However, you can accomplish something similar to what you want by using optional Ints.
var someOptionalInts: [Int?] = [nil, nil, nil, nil]
Hi @timswift,
If there is a reason to store nil
in the array, then you need to declare it as Int?
rather than Int
.
Secondly, is there a reason for 4 nils? If you want to simply store a value as uninitialized
because one of your values could be 0, then you can use a constant of a value that would not be in your range of values, that way you can still use Ints.
let myNull:Int = -12345
var someInts:[Int] = [myNull, myNull, myNull, myNull]
you can check if a value is the same as myNull then you know it is not a value from the range
cheers,
This topic was automatically closed after 166 days. New replies are no longer allowed.