I am trying to convert Swift 3 to Swift 4 for a repo on github. Here is a function that blocks me.
func times(_ n: Int) -> String {
return (0..<n).reduce("") { $0 + self }
}
The error Xcode gives is:
"Cannot invoke 'reduce' with an argument list of type '(String, (String) -> String)'"
I looked at Apple's official page and found reduce(_:_:)
and reduce(into:_:)
, and someone's question. Have tried the code below but I still can't get it to work. Please point out what I am missing.
return (0..<n).character.reduce("") { string, character in
(0..<n) + self }
return (0..<n).character.reduce("") { $0 + self }
Here $0
refers to the closure's first argument (I think). Then we can self property to refer to the current instance within its own instance methods.
Your closure will be receiving two parameters and you're only using one ($0). You could use $0.0 in the closure or simply use the string constructor that does the same thing without reduce:
func times(_ n: Int) -> String
{ return String(repeating:self, count:n) }
OR, if you want to use Python like multiplication to repeat a string, you could add an operator:
extension String
{
static func *(lhs:String,rhs:Int) -> String
{ return String(repeating:lhs, count:rhs) }
}
// then, the following will work nicely:
"blah " * 10 // ==> "blah blah blah blah blah blah blah blah blah blah "