Menu
CoddyTech

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 them as one date string, joined with hyphens (-).

A function cannot capture what print() shows, so build the string yourself and return it. You can join strings with +: formatDate(year: "2024", month: "01", day: "15") returns "2024-01-15".

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

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

Practice on your own: Swift playground