how to use separator param of print in swift2 - swift

Sorry for newbee question.
I really do not know how to use separator param in print
var str = "Hello, playground"
var strs = ["abc","def"]
print(str)
print(strs, separator: ",", terminator: "")
print(str, separator: ",", terminator: "\n")

print accepts its arguments separately, so you can do this:
print("abc", "def", separator: ",")
But you have an array of strings, so you should do this:
print(strs.joinWithSeparator(","))

print ("rob" ,"mark" , "hanna" , separator:"$") // prints rob$mark$hanna
To use separator we need to pass multiple string inside print function.

Related

Any way to override the swift built in print function including constant variables? (#line, #function etc)

I want to be able to override the default Swift standard library print function and include the line number and function name. I have tried several methods such as
public func print(_ items: Any..., separator: String = \(#line), terminator: String = #function {
let output = items.map { "\(terminator) \(separator) -> \($0)" }.joined(separator: " ")
Swift.print(output, terminator: "\n")
}
This correctly prints out the function name of the calling method, however the line number is set to the line number of the print function. I therefore tried changing the separator type to Int and passing #line to it as its default value.
This results in an "ambiguous use of function" error, and changing the signature doesn't help either as the default implementation is called in preference to my function.
I have looked at extensions and even swizzling but neither of these seem fruitful in this instance.
So it seems that in my case a signature change does solve the issue. By being specific about the type passed to the items argument, my custom method is called.
public func print(_ items: String..., filename: String = #file, function : String = #function, line: Int = #line, separator: String = " ", terminator: String = "\n") {
let pretty = "\(URL(fileURLWithPath: filename).lastPathComponent) [#\(line)] \(function)\n\t-> "
let output = items.map { "\($0)" }.joined(separator: separator)
Swift.print(pretty+output, terminator: terminator)
}
Note that all the print statements I care about pass Strings. The default implementation is called otherwise:
print(1+1)
// 2
print("Hello, World!")
// ExampleVC.swift [#101] viewDidLoad()
// -> Hello, World!
print("Hello", "World", separator: ", ", terminator: "!\n")
// ExampleVC.swift [#101] viewDidLoad()
// -> Hello, World!

How to print Escape Sequence characters in Swift?

Sorry if the title is not clear.
What I mean is this:
If I have a variable, we'll call that a, with a value of "Hello\nWorld", it would be written as
var a = "Hello\nWorld
And if I were to print it, I'd get
Hello
World
How could I print it as:
Hello\nWorld
I know this is a little old however I was looking for a solution to the same problem and I figured out something easy.
If you're wanting to print out a string that shows the escape characters like "\nThis Thing\nAlso this"
print(myString.debugDescription)
Here's a more complete version of #Pedro Castilho's answer.
import Foundation
extension String {
static let escapeSequences = [
(original: "\0", escaped: "\\0"),
(original: "\\", escaped: "\\\\"),
(original: "\t", escaped: "\\t"),
(original: "\n", escaped: "\\n"),
(original: "\r", escaped: "\\r"),
(original: "\"", escaped: "\\\""),
(original: "\'", escaped: "\\'"),
]
mutating func literalize() {
self = self.literalized()
}
func literalized() -> String {
return String.escapeSequences.reduce(self) { string, seq in
string.replacingOccurrences(of: seq.original, with: seq.escaped)
}
}
}
let a = "Hello\0\\\t\n\r\"\'World"
print("Original: \(a)\r\n\r\n\r\n")
print("Literalized: \(a.literalized())")
You can't, not without changing the string itself. The \n character sequence only exists in your code as a representation of a newline character, the compiler will change it into an actual newline.
In other words, the issue here is that the "raw" string is the string with the actual newline.
If you want it to appear as an actual \n, you'll need to escape the backslash. (Change it into \\n)
You could also use the following function to automate this:
func literalize(_ string: String) -> String {
return string.replacingOccurrences(of: "\n", with: "\\n")
.replacingOccurrences(of: "\t", with: "\\t")
}
And so on. You can add more replacingOccurrences calls for every escape sequence you want to literalize.
If "Hello\nWorld" is literally the string you're trying to print, then all you do is this:
var str = "Hello\\nWorld"
print(str)
I tested this in the Swift Playgrounds!
Late to the party but the answer to this question is to map the String UnicodeScalarView Unicode.Scalar elements converting them to escaped ascii strings. Then you can simply join back the string:
extension Unicode.Scalar {
var asciiEscaped: String { escaped(asASCII: true) }
}
extension StringProtocol {
var asciiEscaped: String {
unicodeScalars.map(\.asciiEscaped).joined()
}
}
print("Hello\nWorld".asciiEscaped) // Hello\nWorld
Just use double \
var a = "Hello\\nWorld"

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?
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")
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.

Replace all characters in a String in Swift

Just trying to do a play around with Swift String. I want to replace all the characters in a String to a blank space.
inputString = "This is a String"
outputString = " "
How could I achieve this in swift?
You can use the map function to replace any character with another:
String("foo".characters.map { _ in Character(" ") })
One possible way:
outputString = String(count: inputString.characters.count, repeatedValue: (" " as Character))
Another way:
let outputString = inputString.replacingOccurrences(of: "[^\\s]",
with: " ",
options: .regularExpression,
range: inputString.startIndex..<inputString.endIndex)
So given an input String of n chars you want another String of n blank spaces, right?
let inputString = "This is a String"
let outputString = String([Character](count: inputString.characters.count, repeatedValue: " "))

How does this Play 2 ScalaTemplates code work

Please explain the code below:
#title(text: String) = #{
text.split(' ').map(_.capitalize).mkString(" ")
}
<h1>#title("hello world")</h1>
A breakdown of the reusable code block #title(text: String)
text.split( ' ' ) separates the text into a List by splitting the string by ' ', e.g. "hello world" would become ["hello", "world"]
map(_.capitalize) iterates the List, calls capitalize on each element, and returns the new List, e.g. ["hello", "world"] becomes ["Hello", "World"]. This blog post give a good overview of _.
mkString(" ") converts the List back to a String by joining the string with " ", e.g. ["Hello", "World"] becomes "Hello World"
In summary, #title(text: String) capitalizes all words in a String.
The <h1>#title("hello world")</h1> is how you could ouput the result in a ScalaTemplate.