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 .
C/Obj-C interop at a glance (no iOS specifics) is a free Swift Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)C random example
Call platform C functions (e.g., arc4random_uniform on Apple, random() on Linux). Keep examples tiny and portable.
#if canImport(Darwin)
import Darwin
let r = arc4random_uniform(100) // 0..99
print("random:", r)
#else
import Glibc
let r = UInt32(random() % 100) // 0..99 (demo)
print("random:", r)
#endifFoundation bridges
Foundation types bridge naturally: String⇄NSString, [Any]⇄NSArray, [Key:Any]⇄NSDictionary.
import Foundation
// String ↔ NSString bridge is seamless
let swiftString: String = "hello"
let ns: NSString = swiftString as NSString
print(ns.uppercased) // via NSString API
let back: String = ns as String
print(back + " world")
// NSArray / NSDictionary bridge to Swift collections
let nsArray: NSArray = ["a", "b", "c"]
let swiftArray = nsArray as! [String]
print(swiftArray.joined(separator: ","))
let nsDict: NSDictionary = ["lang": "Swift", "year": 2014]
let swiftDict = nsDict as! [String: Any]
print(swiftDict["lang"] as? String ?? "-")NSError → throws
Objective-C NSError** parameters import as throws. Use try/do-catch—no manual pointers needed.
import Foundation
// Many Obj-C methods that take NSError** are imported as throwing in Swift.
let fm = FileManager.default
// Create a temporary file, then remove it with "try".
let tmp = (NSTemporaryDirectory() as NSString).appendingPathComponent("demo.txt")
FileManager.default.createFile(atPath: tmp, contents: Data("hi".utf8), attributes: nil)
do {
try fm.removeItem(atPath: tmp) // was NSError** in Obj-C → throws in Swift
print("removed ok")
} catch {
print("remove failed:", error)
}Expose Swift to Obj-C
Annotate Swift APIs with @objc/@objcMembers (and inherit from NSObject) to make them visible to Objective-C in mixed codebases.
import Foundation
@objcMembers
class Adder: NSObject {
dynamic var last: Int = 0
@objc func add(_ a: Int, _ b: Int) -> Int { last = a + b; return last }
}
let a = Adder()
print(a.add(2, 3)) // 5
print(a.last) // 5
// In mixed projects, Obj-C can call Adder via the generated Swift header.NSError bridging answer
Quick check: How are NSError** APIs imported?
Recap
Recap:
- Import Darwin/Glibc and call simple C APIs.
- Use Foundation bridges for strings/collections.
- Objective-C NSError** maps to Swift throws.
Frequently asked questions
Is the “C/Obj-C interop at a glance (no iOS specifics)” lesson free?
Yes — the full text of “C/Obj-C interop at a glance (no iOS specifics)” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.
What will I learn in “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 . You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Swift Academy?
No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “C/Obj-C interop at a glance (no iOS specifics)” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Swift Academy lesson?
Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Swift scripts (swift shebang), command-line tools
- C/Obj-C interop at a glance (no iOS specifics)
- Packaging binaries with SPM