Is there a way to call C routines from Swift?
A lot of iOS / Apple libraries are C only and I'd still like to be able to call those.
For example, I'd like to be able to call the objc runtime libraries from swift.
In particular, how do you bridge iOS C headers?
Unlike Android which needs a special API (the NDK) to support native development, iOS supports it by default. C or C++ development is more straightforward with iOS because of a feature called 'Objective-C++'.
You can use Objective-C and Swift files together in a single project, no matter which language the project used originally. This makes creating mixed-language app and framework targets as straightforward as creating an app or framework target written in a single language.
Swift is easier to read and easier to learn than Objective-C. Objective-C is over thirty years old, and that means it has a more clunky syntax. Swift streamlines code and more closely resembles readable English, similar to languages like C#, C++, JavaScript, Java, and Python.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With