Take advantage of raw strings in Swift 5
Swift 5 comes with enhancement in string literals delimiters to support Raw Text.
Let’s go with examples
Use of # delimiter
We can use # delimiter with start and end of the strings to use less escape sequences.
fileprivate func useOfHashDelimiter() {
let stringSwift4 = "This is \"Swift 4.x\"."
print(stringSwift4)
let stringSwift5 = #"This is "Swift 5.x"."#
print(stringSwift5)
}
Output:
This is “Swift 4.x”.
This is “Swift 5.x”.
Use of variables with # delimiter
We can use variable with string like \#(variableName)
fileprivate func useOfVariableWithString() {
var intSwift = 4
let stringSwift4 = "This is \"Swift \(intSwift).x\" with variable."
print(stringSwift4)
intSwift = 5
let stringSwift5 = #"This is "Swift \#(intSwift).x" with variable."#
print(stringSwift5)
}
Output:
This is “Swift 4.x” with variable.
This is “Swift 5.x” with variable.
Multiline String with # delimiter
We can use # delimiter in multiline strings too.
fileprivate func withMultilineString() {
let intSwift = 5
let multiline = #"""
This is
Swift \#(intSwift).
"""#
print(multiline)
}
Output:
This is
Swift 5.
Conclusion
Swift is getting more stable day by day!
If you have any questions, comments, suggestions or feedback then contact me on Twitter @ashishkakkad8. I am retweeting many tips on my wall of twitter, you can follow me for updates of iOS.
Happy Coding 🙂
References
Behind the Proposal — SE-0200 Enhancing String Literals Delimiters to Support Raw Text
Originally published at ashishkakkad.com on April 9, 2019.