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.
    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.
    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

senior

What is the difference between static func and class func in Swift?

expert

Why can not we just use weak everywhere and forget about unowned ?

middle

What are the differences between functions and methods in Swift?

Bình luận

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

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