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
// WorldYou 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 WorldThe print() function can also accept multiple items separated by commas. By default, they're joined with spaces:
print("Swift", "is", "fun")
// Output: Swift is funYou can customize the separator using the separator parameter:
print("2024", "01", "15", separator: "-")
// Output: 2024-01-15Challenge
EasyWrite 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 valuemonth(String): The month valueday(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
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorCompound AssignmentRecap - Simple MathComparison Operators7Basic IO
Print FunctionString InterpolationReadLine InputType ConversionRecap - Till 120Recap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesArgument LabelsRecap - Sigma FunctionRecap - Validation FunctionDefault Values13Iterating Over Sequences
Iterating Over ElementsThe Enumerated MethodIterating Over Strings P1Iterating Over Strings P22Variables
Let vs VarType AnnotationsNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator8Bill Split Calculator
Welcome MessageGetting Input3Optionals
What Are OptionalsUnwrapping With If LetGuard LetNil Coalescing OperatorRecap - Safe Unwrapping9Loops
For-In LoopWhile LoopRepeat-While LoopBreakContinueRecap - FactorialRanges In LoopsNested LoopRecap - Dynamic InputPractice on your own: Swift playground