0Pricing
Swift Academy · Lesson

C/Obj-C interop at a glance (no iOS specifics)

Import C system modules, call simple POSIX/C APIs, and use Foundation bridges (String/NSString, arrays/dictionaries). See how Objective-C NSError** becomes Swift throws .

Interop map

This is a quick tour of interop:

  • C: import system modules and call POSIX helpers
  • Foundation: String/NSArray/NSDictionary bridges
  • NSError → Swift throws

C imports & pointers

Swift can call many C APIs directly. Use conditional import for portability and convert char* with String(cString:).

// Import the platform C module: Darwin (Apple) or Glibc (Linux)
#if canImport(Darwin)
import Darwin
#else
import Glibc
#endif

// Use C getenv (returns C pointer) and strlen
if let cPtr = getenv("USER") {
    let name = String(cString: cPtr)   // bridge C char* -> Swift String
    print("Hello,", name)
} else {
    print("Hello, anonymous")
}

// strlen works on C strings:
let cString: [CChar] = Array("swift".utf8).map { CChar($0) } + [0]
let len = strlen(cString)
print("strlen(s) =", len)

All lessons in this course

  1. Swift scripts (swift shebang), command-line tools
  2. C/Obj-C interop at a glance (no iOS specifics)
  3. Packaging binaries with SPM
← Back to Swift Academy