Ad space (banner)
๐ŸฆSwift Lessons
Lesson 26 / 68

Default Parameter Values

In this lesson you will learn how to give a Swift parameter a default value so callers can leave it out. This is for anyone searching for "Swift default parameter how to use".

Writing = value on a parameter sets a default that is used automatically when the caller omits that argument. Picture an order form where leaving a field blank gets you the usual house set.

The sample code defines func greet(name: String = "Guest"), which handles both greet(name: "Alice"), where a name is supplied, and greet(), where nothing is passed.

A common stumbling block for beginners is the ordering. Letting callers omit arguments gives you a flexible function that serves both the simple case and the finely tuned one, and combining defaults with named arguments makes it read better still.

In real-world development, defaults are common in functions that usually take the same value but occasionally need a special one.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Swift directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)