SyntaxStudy
Sign Up
Swift Beginner 1 min read

Swift vs Objective-C

Swift replaced Objective-C as Apple's primary language. Objective-C had a verbose bracket-based syntax inherited from Smalltalk; Swift uses a cleaner dot-notation and modern language features. Swift interoperates fully with Objective-C — you can use existing Objective-C frameworks and gradually migrate codebases. The @objc attribute exposes Swift declarations to Objective-C. Key Swift improvements over Objective-C include optionals for null safety, generics, value types (structs/enums), protocol extensions, and significantly better type inference.
Example
// Objective-C style (verbose):
// NSString *name = @"Alice";
// NSArray *numbers = @[@1, @2, @3];
// [numbers enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//     NSLog(@"%@", obj);
// }];

// Swift equivalent (clean):
let name = "Alice"
let numbers = [1, 2, 3]
numbers.forEach { print($0) }

// @objc interoperability
import Foundation

class MyService: NSObject {
    @objc func greet(_ name: String) -> String {
        return "Hello, \(name)"
    }
}

// Swift-only features
struct Point {
    var x: Double
    var y: Double

    func distance(to other: Point) -> Double {
        let dx = x - other.x
        let dy = y - other.y
        return (dx * dx + dy * dy).squareRoot()
    }
}

let a = Point(x: 0, y: 0)
let b = Point(x: 3, y: 4)
print(a.distance(to: b))  // 5.0