Answer the question
In order to leave comments, you need to log in
How can I repeat an element count times in a function?
Condition:
Write a function called repeatString which repeats the given String src exactly count times.
repeatStr(6, "I") // "IIIIII"
repeatStr(5, "Hello") // "HelloHelloHelloHelloHello"
Initial function:
func repeatStr(_ n: Int, _ string: String) -> String {
// Code here
return ""
}
Answer the question
In order to leave comments, you need to log in
Three options at a glance (by difficulty level):
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) }
}
repeatElement("asd", count: 5).joined()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question