Syntax Quiz - Languages Swift
Free practice quiz: Syntax (Languages Swift). 50 multiple-choice questions with answers and explanations. Play online, no sign-up needed.
Play all 50 questions freeSample questions
Which keyword is used to declare a constant in Swift?
- var
- let
- const
- constant
Show answer
Answer: B. let
In Swift, the `let` keyword is used to declare a constant, which means its value cannot be changed after it's initially assigned. The `var` keyword is used for variables.
How do you declare a property within a struct in Swift?
- var propertyName: DataType
- let propertyName: DataType
- Both var and let propertyName: DataType
- define propertyName: DataType
Show answer
Answer: C. Both var and let propertyName: DataType
Properties within a Swift struct can be declared using either the `var` keyword for mutable properties or the `let` keyword for constants.
What is the correct way to declare an implicitly unwrapped optional String in Swift?
- var name: String?
- var name: String!
- var name: String
- var name: Optional<String>
Show answer
Answer: B. var name: String!
An implicitly unwrapped optional is declared by appending an exclamation mark (`!`) to the type. It's treated like an optional but can be accessed directly without unwrapping, assuming it always has a value.
Which syntax is used for accessing a named element in a Swift tuple?
- myTuple.0
- myTuple.first
- myTuple.name
- myTuple[0]
Show answer
Answer: C. myTuple.name
If a tuple has named elements, you can access them using dot notation with their names (e.g., `myTuple.name`). Unnamed elements are accessed using their zero-based index (e.g., `myTuple.0`).
What is the Swift keyword used to refer to the current instance of a type?
- self
- this
- current
- instance
Show answer
Answer: A. self
The `self` keyword is used within an instance method or computed property to refer to the current instance of the type.