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.
1 2 3 4 5 6 |
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)
1 2 3 4 5 6 7 8 |
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.
1 2 3 4 5 6 7 8 |
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