0
0
Swiftprogramming~10 mins

Default parameter values in Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a function with a default parameter value.

Swift
func greet(name: String = [1]) {
    print("Hello, \(name)!")
}
greet()
Drag options to blanks, or click blank then click option'
A"User"
B"Guest"
C"Friend"
D"Visitor"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the default value in quotes.
Using a colon instead of an equals sign for the default value.
2fill in blank
medium

Complete the code to call the function with a custom argument.

Swift
func greet(name: String = "Guest") {
    print("Hello, \(name)!")
}
greet([1])
Drag options to blanks, or click blank then click option'
A"Visitor"
BVisitor
Cname
D"name"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the argument without quotes.
Passing the parameter name instead of a value.
3fill in blank
hard

Fix the error in the function definition by completing the default parameter value.

Swift
func multiply(number: Int = [1]) -> Int {
    return number * 2
}
print(multiply())
Drag options to blanks, or click blank then click option'
Anil
B"2"
Cnumber
D2
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string "2" instead of integer 2.
Using nil as a default value for a non-optional parameter.
4fill in blank
hard

Fill both blanks to define a function with two parameters, one with a default value.

Swift
func describe(age: Int, city: String = [1]) {
    print("Age: \(age), City: \(city)")
}
describe(age: [2])
Drag options to blanks, or click blank then click option'
A"Unknown"
B30
C"Unknown City"
Dage
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number as a default for a String parameter.
Not providing the required age argument in the function call.
5fill in blank
hard

Fill all three blanks to create a function with default parameters and call it with custom arguments.

Swift
func order(item: String = [1], quantity: Int = [2], price: Double = [3]) {
    print("Order: \(quantity) \(item)(s) at $\(price) each")
}
order(item: "Book", quantity: 3, price: 12.99)
Drag options to blanks, or click blank then click option'
A"Pen"
B1
C9.99
D"Notebook"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong types for default values.
Not matching the parameter order in the function call.