0

I have a simple array and would like to loop through it and replace all elements with false but am having a problem with the for in loop. An example of what I have done is below. I am new to Swift so any help with what the loop should look like would be sincerely appreciated.

struct ClubMembers {
    var name: String
    var active: Bool
}

func sampleMembers() -> [ClubMembers] {
    let member1 = ClubMembers(name: "David", active: false)
    let member2 = ClubMembers(name: "John", active: false)
    let member3 = ClubMembers(name: "Mitchell", active: true)

    return [member1, member2, member3]
}
3
  • 3
    There's no for loop in the code you posted. Please show the code that you have tried and clearly explain what issues you are having. Commented Jun 22, 2018 at 21:08
  • for _ in sampleMembers() { _ = false } Commented Jun 22, 2018 at 21:20
  • 1
    Edit your question. Commented Jun 22, 2018 at 21:20

2 Answers 2

1

You are attempting:

for _ in sampleMembers() { _ = false }

The _ means that you wish to ignore the value. You don't want to ignore the value, you need it.

for member in sampleMembers() { member.active = false }

But this has a couple of issues. member is read-only and the array is gone as soon as this line completes.

So you need to iterate each index of the array and update each value:

var members = sampleMembers()
for i in members.indices {
    members[i].active = false
}
Sign up to request clarification or add additional context in comments.

Comments

0

example:

struct ClubMembers {
    var name: String
    var active: Bool
}

func sampleMembers() -> [ClubMembers] {
    let member1 = ClubMembers(name: "David", active: true)
    let member2 = ClubMembers(name: "John", active: true)
    let member3 = ClubMembers(name: "Mitchell", active: true)

    return [member1, member2, member3]
}

var array = sampleMembers()

for i in 0..<array.count {
    array[i].active = false
}

for i in 0..<array.count {
    print(array[i].active)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.