bmaliel
bmaliel

Reputation: 353

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?

Upvotes: 3

Views: 2631

Answers (5)

Americana American
Americana American

Reputation: 59

var symbol = "*"

print(String(repeating: symbol, count: 4))

// "****"

Upvotes: 0

Mustafa
Mustafa

Reputation: 20564

Combining solutions proposed by rintaro and Jeremy Pope, you can do exactly what you want:

func * (left: String, right: Int) -> String {
    return join("", Repeat(count: right, repeatedValue: left))
}

var symbol: String = "*"
println(symbol * 4)

Upvotes: 2

rintaro
rintaro

Reputation: 51911

There is no builtin operator for that in Swift.

You can use Repeat and join instead.

var symbol = "*"
println(join("", Repeat(count: 4, repeatedValue: symbol)))

Repeat(count: 4, repeatedValue: symbol) virtually creates [symbol, symbol, symbol, symbol], then join("", ...) joins them using separator "".

Upvotes: 2

Jeremy Pope
Jeremy Pope

Reputation: 3352

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)

Upvotes: 2

rshankar
rshankar

Reputation: 3085

Can you try this - println(String(count: 4, repeatedValue: Character("*")))

Upvotes: 0

Related Questions