wing
wing

Reputation: 151

How to call standard C library from Swift?

I want to use C libraries such as stdio.h, stdlib.h, etc. in my swift application. But I can't import . How can I do?

import <stdio.h> // BAD
#include <stdio.h> // BAD
#import <stdio.h> // BAD
import Foundation // cannot use printf etc.

Upvotes: 5

Views: 2551

Answers (2)

Chris Hatton
Chris Hatton

Reputation: 828

To import C functions in pure Swift on the OS-X platform use:

import Darwin

This can be seen as one of the sub-imports inside Foundation.swift, but importing it individually avoids potentially unnecessary processing of Cocoa and other iOS/OSX framework modules.

NeilJaff's answer works because it causes Foundation and all submodules to be imported, but import Darwin is more targeted.

Upvotes: 6

Neil Japhtha
Neil Japhtha

Reputation: 875

Create a Bridging Header

  • Create an Obj-C header file
  • Add the import statements
  • Go to your projects build settings
  • Find the Objective-C Bridging Header setting.
  • Set it to the path/of/your/file
  • The files you've imported into the header, will then be able to be used In all Swift files.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

Upvotes: 4

Related Questions