Question: What are optionals in Swift and how to unwrap optionals??
|
Answer: The Optionals in Swift represent values that may or may not exist. They are used to handle the absence
of a value in a safe way.
Optionals can be unwrapped using optional binding, forced unwrapping with the ! operator,
or by using optional chaining.
|
Question: Can you explain the difference between a struct and a class in Swift. When would you use each?
|
Answer: In Swift, structs and classes are both used to define custom data types, but they have some differences.
Structs are value types, meaning they are copied when passed around, while classes are reference types, meaning they
are passed by reference.
Structs are suitable for small, simple data types, while classes are used for more complex objects
or when inheritance is needed.
|
Question: What is a closure in Swift?
|
Answer: A closure is a self-contained block of functionality that can be passed around and used in your code.
Closures capture and store references to any constants and variables from the context in which they are defined.
Here is an example:
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map({ (number: Int) -> Int in
return number * 2
})
print(doubled) // Output: [2, 4, 6, 8, 10]
|
Question: What is the difference between a class method and an instance method in Swift?
|
Answer: A class method is a method that is called on the type itself, whereas an instance method is called
on an instance of the type.
Class methods are prefixed with the keyword class or static, whereas instance methods are not.
|
Question: Can you explain the concept of protocols in Swift?
|
Answer: In Swift Protocols define a blueprint of methods, properties, and other requirements that suit a
particular task or piece of functionality.
They are useful for defining a set of rules or behaviors that types can adopt,
enabling polymorphism and allowing for more flexible and modular code.
|
Question: What is type casting in Swift?
|
Answer: In Swift type casting is the process of converting one type of value to another.
It can be done using the as? or as! operators for conditional and forced type casting respectively.
Type casting is useful when working with hierarchies of related types, such as class inheritance or protocol conformance.
|
Question: What is a didSet property observer in Swift?
|
Answer: The didSet is a property observer in Swift that is called immediately after the value of a
property is set. It provides a way to observe and respond to changes in property values.
didSet is particularly useful for performing side effects or additional logic when a property's value changes.
|