Text Templates in Swift

Here’s the Swift translation of the Text Templates example:

Our first program demonstrates the use of string interpolation and multi-line strings in Swift, which are similar to text templates in other languages. Here’s the full source code:

import Foundation

func main() {
    // We can create a new string with interpolation.
    // String interpolation in Swift is enclosed in \(...).
    let t1 = "Value is \(5)\n"
    print(t1)
    
    // We can use multi-line string literals for more complex templates.
    // These are enclosed in triple quotes.
    let t2 = """
    Name: \(PersonName(name: "Jane Doe").name)
    """
    print(t2)
    
    // We can use dictionaries for key-value pairs.
    let dict = ["Name": "Mickey Mouse"]
    let t3 = "Name: \(dict["Name"] ?? "")\n"
    print(t3)
    
    // Conditional statements can be used within string interpolation.
    let t4 = "Result: \(5 > 0 ? "yes" : "no")\n"
    print(t4)
    
    // We can use loops within string interpolation to iterate over collections.
    let languages = ["Swift", "Rust", "C++", "C#"]
    let t5 = "Range: \(languages.map { $0 }.joined(separator: " "))\n"
    print(t5)
}

// Helper struct for demonstration
struct PersonName {
    let name: String
}

main()

To run the program, save it as templates.swift and use swift command:

$ swift templates.swift
Value is 5

Name: Jane Doe
Name: Mickey Mouse
Result: yes
Range: Swift Rust C++ C#

In Swift, we don’t have a separate template engine built into the standard library. Instead, we use string interpolation and multi-line strings to achieve similar functionality. String interpolation in Swift is very powerful and can include complex expressions, making it a flexible tool for creating dynamic strings.

The \(...) syntax in Swift strings allows us to embed expressions directly into string literals. This is similar to the {{...}} syntax in some template engines.

Swift’s multi-line string literals (enclosed in triple quotes) allow us to create more complex string templates that span multiple lines without needing to escape newline characters.

Conditional logic can be included directly in string interpolation using the ternary operator ?:.

For iterating over collections, we can use higher-order functions like map and joined within string interpolation to create a formatted string from an array.

While this approach doesn’t offer all the features of a full-fledged template engine, it provides a straightforward way to create dynamic strings in Swift.