1. Type Safety: Swift is a type-safe language, which means that every variable must be declared with a specific type. For example, if you want to declare a variable called “name” that will store a string, you would write the following:

let name: String = “John”

2. Optionals: Optionals allow you to check if a value is present or not. This helps to prevent runtime errors and makes code more readable. For example, if you have a variable that may or may not contain a value, you can use an optional to check if the value is present before attempting to use it.

let optionalName: String? = “John”

if let name = optionalName {
print(“Name is (name)”)
}

3. Closures: Closures are self-contained blocks of code that can be passed around and used in your code. They are often used to simplify asynchronous programming. For example, you can use a closure to execute a block of code after a network request has completed.

let request = URLRequest(url: URL(string: “https://example.com”)!)

URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
print(“Data: (data)”)
}
}.resume()

4. Generics: Generics allow you to write code that can work with any type, without the need to specify the exact type. This makes code more flexible and reusable. For example, you can write a generic function that can sort any type of array, without needing to specify the exact type of array.

func sort(_ array: [T]) -> [T] {
return array.sorted()
}

let names = [“John”, “Paul”, “George”, “Ringo”]
let sortedNames = sort(names) // [“George”, “John”, “Paul”, “Ringo”]

Leave a Reply

Your email address will not be published. Required fields are marked *