Getting Started
Swift is a type-safe, compiled language with modern features like optionals, closures, generics, and protocol-oriented programming.
// Variables & Constants
var name = "iOS Developer"
let pi = 3.14159
// Data Types
let age: Int = 25
let price: Double = 99.99
let isActive: Bool = true
// Optionals
var email: String? = nil
if let validEmail = email {
print(validEmail)
}
// Functions
func greet(name: String) -> String {
return "Hello, \(name)!"
}
// Closures
let numbers = [1, 2, 3, 4]
let doubled = numbers.map { $0 * 2 }
Objective-C extends C with object-oriented capabilities and message-passing syntax. It uses header files (.h) and implementation files (.m).
// Interface (Person.h)
@interface Person : NSObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, assign) NSInteger age;
- (void)sayHello;
@end
// Implementation (Person.m)
@implementation Person
- (void)sayHello {
NSLog(@"Hello, my name is %@", self.name);
}
@end
Protocols define a blueprint of methods, and delegates implement them:
// Swift
protocol DataFetcherDelegate: AnyObject {
func didFetchData(_ data: [String])
}
class DataManager {
weak var delegate: DataFetcherDelegate?
func fetch() {
// ... fetch data
delegate?.didFetchData(["Item1", "Item2"])
}
}
Swift uses Automatic Reference Counting (ARC) to manage memory. Both Swift and Objective-C use reference counting; avoid retain cycles with weak references.
Temperature with properties for celsius and fahrenheit. Add computed properties and a protocol Convertible with a convert() method. Implement a delegate pattern between a WeatherService and a WeatherViewController.