Reputation:
var array:[Int] = []
var index = 5
if array[index] == nil {
array[index] = 1
}
Currently Xcode states that an int can not take the value of nil. So this code doesn't work. Is there any way to produce the same effect or verifying if a specific index is empty?
Upvotes: 1
Views: 2873
Reputation: 919
Declaring the property as:
var array:[Int] = []
the array property itself can be empty (no values) - as it is when you declare it as you did above, but it cannot contain nil values, so a check for nil shouldn't be necessary.
If you are checking to see if the array is empty, calling array.isEmpty, or checking array.count > 0 should do the trick.
If you need to store empty (non-initialized Int's/nil) in the array, then the array would be declared as:
var array:[Int?] = []
in which case the array could hold integers, or nil values. In this case you would need to safely unwrap the optional prior to using it, such as:
var array:[Int?] = [1, 2, nil, 4]
for item in array {
if let item = item {
print("item is \(item)")
} else {
print("item is nil")
}
}
// item is 1
// item is 2
// item is nil
// item is 4
Upvotes: 0
Reputation: 70245
If the array can hold nil
values, then its type must be an optional
- as such:
var array:[Int?] = []
In general, when accessing an array based on an index you need to confirm that the index is in range. You might extend Array with
extension Array {
func ref (i:Index) -> Element? {
return i < count ? self[i] : nil
}
}
and then use as:
array.ref(i)
[Note: this will confound nil
as 'out of range' with nil
as 'value in optional array']
Upvotes: 1