Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift, how do I set every element inside an array to nil?

Tags:

ios

swift

var roomsLiveStates = [Firebase?]()

for ref in roomsLiveStates {
        if ref != nil {
                ref = nil
            }
        }
}

This doesn't seem to work.

like image 214
TIMEX Avatar asked Dec 08 '22 02:12

TIMEX


2 Answers

You can also use a map:

roomsLiveStates = roomsLiveStates.map { _ in nil }

This is less code and a good habit to get into for other cases where you may want to create a processed copy of an array without mutating the original.

like image 24
Eric Avatar answered Jan 21 '23 01:01

Eric


You can just set each to nil:

for index in 0 ..< roomsLiveStates.count {
    roomsLiveStates[index] = nil
}

As The Swift Programming Language says in its Control Flow discussion of for syntax:

This example prints the first few entries in the five-times-table:

for index in 1...5 {
    println("\(index) times 5 is \(index * 5)")
}

... In the example above, index is a constant whose value is automatically set at the start of each iteration of the loop. As such, it does not have to be declared before it is used. It is implicitly declared simply by its inclusion in the loop declaration, without the need for a let declaration keyword.

As this says, the index is a constant. As such, you can not change its value.

like image 140
Rob Avatar answered Jan 21 '23 00:01

Rob