How to modify a variable/property itself (instead of its value) through an array?

Say I have something like this:

class Thing {}
var thing1: Thing? = Thing()
var thing2: Thing? = Thing()
var thing3: Thing? = Thing()

var array: [Thing?] = [thing1, thing2, thing3]

Is there any “idiomatic” way to make thing2 == nil through the array?

array[1] = nil just makes array == [thing1, nil, thing3] but thing2 remains unmodified, of course.


In the actual code that I have in a project, I have to write a lot of lines like the following:

func clearFlaggedProperties() {
    if self.property1 != nil && self.property1!.shouldClear { self.property1 = nil }
    if self.property2 != nil && self.property2!.shouldClear { self.property2 = nil }
    // and so on...
}

(I only include self to clarify this particular example, and the check for nil is related to a bug involving observers.)

How can I better write all that?


I tried tuples. Although I can modify the property through a tuple, I cannot iterate through a tuple with a for in or forEach, so I still have to write a lot of ifs.

The easiest way is to make Thing a struct, and place Thing? inside a wrapper class that goes in the array

You could do this:

struct Thing { // just to make it easier to construct the array
	var shouldClear = false
}

var array: [Thing?] = Array(repeating: Thing(), count: 3) // for class, you would write a loop
var thing1: Thing? {
	return array[0]
}
var thing2: Thing? {
	return array[1]
}
var thing3: Thing? {
	return array[2]
}

func clearFlaggedProperties() {
	for (index, thing) in array.enumerated() {
		if let thing = thing, thing.shouldClear {
			array[index] = nil
		}
	}
}
1 Like

^^ this is more complicated but probably the “right” way to do it

Terms of Service

Privacy Policy

Cookie Policy