Câu hỏi phỏng vấn Swift
Câu hỏi

What is the difference between let and var in Swift?

Câu trả lời

In Swift, the keywords let and var are used to declare constants and variables, respectively. Here are the key differences between them:

let (Constants)

  • Immutability: Values declared with let are immutable, meaning they cannot be changed once they are set. This ensures that the value remains constant throughout the program.
  • Syntax: To declare a constant, you use the let keyword.
    swift Copy
    let studentName = "Arpit Mishra"
    In this example, studentName is a constant and its value cannot be changed after its initial assignment.
  • Usage: Constants are used when you have values that should not change during the execution of the program, making the code safer and clearer in intent[1][3].

var (Variables)

  • Mutability: Values declared with var are mutable, meaning they can be changed or reassigned after their initial declaration.
  • Syntax: To declare a variable, you use the var keyword.
    swift Copy
    var grade = 7
    In this example, grade is a variable and its value can be changed later in the program.
  • Usage: Variables are used when you need to store values that might change during the execution of the program[1][3].

Summary of Differences

let var
Called constants Called variables
Immutable Mutable
Declared with let keyword Declared wi...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

What is a good use case for an inout parameter?

senior

Explain the difference between weak and unowned references. Provide an example

senior

When to use fileprivate access modifier in Swift?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào