Swift syntax overview
Swift syntax is designed to be clear, concise, and expressive, aiming to enhance readability and developer productivity.
1. Variables and Constants: Variables are declared using var keyword, and constants are declared using let. Example:
swift code
var age = 24
let name = "@hiren_syl"
2. Type Annotations and Type Inference: Swift supports both explicit type annotations and type inference.
swift code
var score: Int = 100
var message = "Hello, World!" // type inferred as String
3. Optionals: Optionals represent the presence or absence of a value. They are declared by appending ? to the type.
swift code
var optionalName: String? = "John"
4. Basic Operators: Swift supports standard operators like arithmetic, comparison, and logical operators.
swift code
let sum = 5 + 3
let isGreater = 10 > 5
5. Control Flow: Swift provides control flow statements such as if, switch, for-in, while, and repeat-while.
swift code
if score >= 90 {
print("Excellent!")
} else if score >= 60 {
print("Pass")
} else {
print("Fail")
}
6. Functions: Functions in Swift are defined using func keyword.
swift code
func greet(name: String) > String {
return "Hello, \(name)!"
}
7. Closures: Closures are self-contained blocks of functionality that can be passed around and used in Swift.
swift code
let greeting = { (name: String) > String in
return "Hello, \(name)!"
}
8. Classes, Structures, and Enums: Swift supports object-oriented programming with classes and structures, and it also has powerful enum types.
swift code
class Person {
var name: String
init(name: String) {
self.name = name
}
}
9. Optionals and Type Casting: Swift provides robust mechanisms for handling optionals and type casting.
swift code
if let unwrappedName = optionalName {
print("Hello, \(unwrappedName)")
}
10. Error Handling: Swift uses do-catch blocks for handling errors.
swift code
do {
let result = try performOperation()
} catch {
print("Error: \(error)")
}
11. Generics: Swift supports generics, enabling you to write flexible and reusable functions and types.
swift code
func repeatItem<T>(item: T, times: Int) > [T] {
var result = [T]()
for _ in 0..<times {
result.append(item)
}
return result
}
12. Memory Management: Swift uses Automatic Reference Counting (ARC) to manage memory automatically.
Comments
Post a Comment