Menu
Coddy logo textTech

Print Function

Part of the Fundamentals section of Coddy's Swift journey — lesson 31 of 86.

You've been using print() throughout this course to display output. Now let's take a closer look at how this function works and explore some of its useful features.

By default, print() adds a newline character at the end of each output, which is why each print statement appears on its own line:

print("Hello")
print("World")
// Output:
// Hello
// World

You can change this behavior using the terminator parameter. This lets you specify what character (or string) should appear at the end instead of a newline:

print("Hello", terminator: " ")
print("World")
// Output: Hello World

The print() function can also accept multiple items separated by commas. By default, they're joined with spaces:

print("Swift", "is", "fun")
// Output: Swift is fun

You can customize the separator using the separator parameter:

print("2024", "01", "15", separator: "-")
// Output: 2024-01-15
challenge icon

Challenge

Easy
Write a function formatDate that takes year, month, and day and returns a formatted date string.

Use the print() function with the separator parameter to join the three date components with a hyphen (-), then capture the result to return it.

Hint: You can use print() with a custom separator to format the output, but since this function needs to return a string, you'll need to construct the formatted string directly by joining the components with "-".

Parameters:

  • year (String): The year value
  • month (String): The month value
  • day (String): The day value

Returns: A formatted date string with components joined by hyphens. Format: year-month-day

Cheat sheet

By default, print() adds a newline character at the end of each output:

print("Hello")
print("World")
// Output:
// Hello
// World

Use the terminator parameter to change what appears at the end instead of a newline:

print("Hello", terminator: " ")
print("World")
// Output: Hello World

The print() function accepts multiple items separated by commas, joined with spaces by default:

print("Swift", "is", "fun")
// Output: Swift is fun

Use the separator parameter to customize how items are joined:

print("2024", "01", "15", separator: "-")
// Output: 2024-01-15

Try it yourself

func formatDate(year: String, month: String, day: String) -> String {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals