Correct way to update an element in an array of strings

Hi All:

I see in the quick reference:

Accessing the value stored in an array is a failable expression because there might not be an element at that index, and so it must be used in a failure context.

Then I also see this:

Changing an element in an array: You can change the value stored in an array variable at an index by using the keyword set = .

In my case I have an array of strings… for example

var Result : []string = array{"hello", "testing", "array"}

I tried to update one element using the set keyword:
set Result[0] = "replaced"

This gave me an error in VSCode:
This invocation calls a function that has the 'decides' effect, which is not allowed by its context.(3512)

The docs give an if statement for “accessing” the array such as
if (Element := ExampleArray[0]): Element but that doesn’t really fit what I am trying to accomplish.

What is the correct way to update an element in the array while being mindful of a possible index-error/out-of-bounds error?

1 Like

I believe you can simply do

# The '{}' is to end the "if" statement if all you want to do is update
# the array's element, otherwise, you can put a colon and do stuff 
# inside the if's block
if (set Array[index] = NewElement) {}
3 Likes

Yep that did the trick

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.