dumbfingers
dumbfingers

Reputation: 7089

Print String using variadic params without comma, newline and brackets in Swift

While I was trying to use Swift's String(format: format, args) method, I found out that I cannot print the formatted string directly without newline(\n) and brackets being added.

So for example, I have a code like this:

func someFunc(string: String...) {
    print(String(format: "test %@", string))
}

let string = "string1"
someFunc(string, "string2")

the result would be:

"test (\n    string1,\n    string2\n)\n"

However, I intend to deliver the result like this:

"test string1 string2"

How can I make the brackets and \n not being printed?

Upvotes: 1

Views: 300

Answers (2)

SArnab
SArnab

Reputation: 585

You will first need to concatenate your list of input strings, otherwise it will print as a list, hence the commas and parentheses. You can additionally strip out the newline characters and whitespace from the ends of the string using a character set.

var stringConcat : String = ''
for stringEntry in string {
    stringConcat += stringEntry.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}

Then just print out the stringConcat.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726689

Since string parameter is a sequence, you can use joinWithSeparator on it, like this:

func someFunc(string: String...) {
    print(string.joinWithSeparator(" "))
}

someFunc("quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog")

Upvotes: 2

Related Questions