@Sir0zha

Как в функции сделать повторение элемента count раз?

Условие:
Write a function called repeatString which repeats the given String src exactly count times.

repeatStr(6, "I") // "IIIIII"
repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"
Начальная функция:
func repeatStr(_ n: Int, _ string: String) -> String {
// Code here
return ""
}
  • Вопрос задан
  • 539 просмотров
Решения вопроса 1
@dotAramis
Три варианта на вскидку (по уровням сложности):
func repeatStr0(_ n: Int, _ string: String) -> String {
            var accumulator = ""
            for _ in 0 ..< n {
                accumulator.append(string)
            }
            return accumulator
        }

        func repeatStr1(_ n: Int, _ string: String) -> String {
            var accumulator = ""
            (0 ..< n).forEach {_ in accumulator.append(string) }
            return accumulator
        }

        func repeatStr2(_ n: Int, _ string: String) -> String {
            return (0 ..< n).reduce(into: "") { s, _ in s.append(string) }
        }


еще 1, бонусом:
repeatElement("asd", count: 5).joined()
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы