Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to mix C and Swift?

Tags:

c

swift

I've studied the basics of Swift and some C. How could I combine C and Swift in one project? Could I ignore Objective-C?

like image 756
SanchelliosProg Avatar asked Jan 28 '15 22:01

SanchelliosProg


People also ask

Can I mix Objective-C and Swift?

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.

Does Swift work with C?

Swift is easy to read and write and more resilient to errors than other languages. It is an open-source language and can be used on many different platforms. It is compatible with Objective-C and can be used to develop software for iOS, macOS, tvOS, watchOS, and Linux.

Is Swift a superset of C?

Unlike Objective-C, which is a proper superset of C, Swift has been built as an entirely new language. Swift cannot compile C code because the syntax is not compatible.

How different is Swift from C?

01. Swift is a general-purpose, high-level programming language which is highly concerned about safety, performance. Objective C is an general purpose language which is considered as superset of C language it was designed in an aim of providing object-oriented capabilities. 02.


1 Answers

It is very much possible to mix Swift and C. In fact it's pretty easy. For example, if you type import Darwin into a playground, you will find all sorts of C functions:

import Darwin

let i = atoi("42")
let path = String.fromCString(getenv("PATH"))

let voidptr = malloc(10 * UInt(sizeof(Int)))
let ptr = UnsafeMutablePointer<Int>(voidptr)
for i in 0..<10 {
    ptr[i] = i
}
let buffer = UnsafeBufferPointer(start: ptr, count: 10)
reduce(buffer, 0, +) // sum(1 to 10) = 45
free(ptr)

There are various convenience conversions, for example in the above code, "42" was automatically converted to a C-style string to be passed into atoi. Similarly, if you declare var i: Int = 0, you can pass that into a C API that takes a C pointer-to-int as f(&i), and arrays are similarly auto-converted to pointers when you pass them in.

See the docs on the Apple website for more info on how you can interact with C from Swift.

like image 200
Airspeed Velocity Avatar answered Sep 26 '22 12:09

Airspeed Velocity