Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print multiple instances of a variable in Swift

In Swift, how can you print out a variable multiple times. Say I had

var symbol = "*"

Can I do something like in JavaScript where you go

console.log(symbol * 4)

When I try to do this in Swift, an error comes back. Any way around this?

like image 933
bmaliel Avatar asked Nov 30 '25 02:11

bmaliel


1 Answers

You can very easily create an operator overload which will make this work.

func * (left: String, right: Int) -> String {
    var multipliedString = left
    for x in 1..<right {
        multipliedString += left
    }
    return multipliedString
}

Put that above your class, and then you can do something like:

println("Hello World" * 1000)
like image 164
Jeremy Pope Avatar answered Dec 02 '25 14:12

Jeremy Pope



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!