How to call C from Swift?
The compiler converts C API to Swift just like it does for Objective-C.
import Cocoa
let frame = CGRect(x: 10, y: 10, width: 100, height: 100)
import Darwin
for _ in 1..10 {
println(rand() % 100)
}
See Interacting with Objective-C APIs in the docs.
Yes, you can of course interact with Apple's C libraries. Here is explained how.
Basically, the C types, C pointers, etc., are translated into Swift objects, for example a C int
in Swift is a CInt
.
I've built a tiny example, for another question, which can be used as a little explanation, on how to bridge between C and Swift:
main.swift
import Foundation
var output: CInt = 0
getInput(&output)
println(output)
UserInput.c
#include <stdio.h>
void getInput(int *output) {
scanf("%i", output);
}
cliinput-Bridging-Header.h
void getInput(int *output);
Here is the original answer.