Bird
0
0

Which of the following is the correct way to assign a function to a variable in Swift?

easy📝 Syntax Q12 of 15
Swift - Functions
Which of the following is the correct way to assign a function to a variable in Swift?
Alet greet = func sayHello() { print("Hello") }
Blet greet = sayHello
Cfunc greet = sayHello()
Dvar greet: sayHello = func()
Step-by-Step Solution
Solution:
  1. Step 1: Recall Swift syntax for assigning functions

    In Swift, you assign a function by its name without parentheses to a variable or constant.
  2. Step 2: Check each option for correct syntax

    let greet = sayHello correctly assigns the function name without calling it. Other options have syntax errors or misuse keywords.
  3. Final Answer:

    let greet = sayHello -> Option B
  4. Quick Check:

    Assign function by name without () = let greet = sayHello [OK]
Quick Trick: Assign function by name only, no parentheses [OK]
Common Mistakes:
  • Adding parentheses when assigning function
  • Using 'func' keyword in assignment
  • Incorrect variable declaration syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Swift Quizzes