ForEach l oop внутри действия кнопки в SwiftUI? - PullRequest
0 голосов
/ 13 апреля 2020

Я понимаю, что ForEach l oop обычно используется для отображения представления. Когда я помещаю ForEach l oop внутри кнопки действия, это в значительной степени говорит мне, что действие кнопки не может соответствовать протоколу представления. Итак, как я могу использовать al oop, чтобы кнопка выполняла несколько действий?

struct SomeView: View {
    var newExercises = [NewExercise]()
    var finalExercises = [Exercise]()

    var body: some View {
        Button(action: {
            ForEach(newExercises) { newExercise in
                //.getExercise() returns an Exercise object
                finalExercises.append(newExercise.getExercise())
            }

        }) {
            Text("Done")
        }
    }
}

Я хочу, чтобы кнопка добавила Exercise (вызывая .getExercise ()) к массиву finalExercises для каждого newExercise в массиве newExercises.

Как я могу go сделать это?

1 Ответ

1 голос
/ 13 апреля 2020

Новый оператор SwiftUI ForEach возвращает View для каждого Element из Array. Для вашего кода вам просто нужно запустить Void, Array<Exercise>.append(newElement: Exercise), а не получить несколько View, поэтому вы можете использовать for l oop, map или Array.forEach(body: (_) throws -> Void).

Если порядок, в котором добавляются newExercises, имеет значение, наиболее элегантным решением будет сопоставление каждого NewExercise из finalExercises с Exercise и добавление результирующего Array<Exercise> с Array<Exercise>.append(contentsOf: Sequence) .

struct SomeView: View {
    @State var newExercises = [NewExercise]()
    @State var finalExercises = [Exercise]()

    var body: some View {
        Button(action: {
            self.finalExercises.append(contentsOf:
                self.newExercises.map { newExercise -> Exercise in
                    newExercise.getExercise()
                }
            )


        }) {
            Text("Done")
        }
    }
}

Если порядок добавления newExercises не имеет значения, вы можете позвонить Array<Exercise>.append(newElement: Exercise) из newExcercises.forEach, что отличается от оператора SwiftUI ForEach:

struct SomeView: View {
    @State var newExercises = [NewExercise]()
    @State var finalExercises = [Exercise]()

    var body: some View {
        Button(action: {
            self.newExercises.forEach { newExercise in
                self.finalExercises.append(newExercise.getExercise())
            }
        }) {
            Text("Done")
        }
    }
}

Способ завершить то, что вы хотите с помощью для l oop, будет простым, но менее элегантным:

struct SomeView: View {
    @State var newExercises = [NewExercise]()
    @State var finalExercises = [Exercise]()

    var body: some View {
        Button(action: {
            for newExercise in self.newExercises {
                self.finalExercises.append(newExercise.getExercise())
            }

        }) {
            Text("Done")
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...