Swift and C language mixed programming tutorials _swift

Source: Internet
Author: User
Tags constant mixed

As a language that can be invoked with OBJECTIVE-C, Swift also has some types and features with C, and if your code is needed, Swift also provides a mixed programming approach to the common C code structure.

Basic data types

Swift provides some basic types such as the char,int,float,double equivalent of the SWIFT basic data type for the C language. However, the core basic types of Swift are not implicitly convertible to each other, such as Int. Therefore, only if your code explicitly asks them to use these types, the Int can be used whenever you want to use it.

type C Swift Type
bool CBool
Char, signed Char CChar
unsigned char Cunsignedchar
Short CShort
unsigned short Cunsignedshort
Int CInt
unsigned int Cunsignedint
Long Clong
unsigned long Cunsignedlong
Long Long Clonglong
unsigned long long Cunsignedlonglong
wchar_t Cwidechar
char16_t CChar16
char32_t CChar32
Float Cfloat
Double Cdouble

Enumeration

Swift introduces any C-style enumeration type that is marked with a macro ns_enum. This means that regardless of whether the enumeration values are defined in the system framework or in custom code, their prefix names will be truncated when they are imported to Swift. For example, look at this OBJECTIVE-C enumeration:

Copy Code code as follows:

Objective-c
typedef ns_enum (Nsinteger, Uitableviewcellstyle) {
Uitableviewcellstyledefault,
UITableViewCellStyleValue1,
UITableViewCellStyleValue2,
Uitableviewcellstylesubtitle
};

In Swift, this is accomplished by:
Copy Code code as follows:

Swift
Enum Uitableviewcellstyle:int {
Case Default
Case Value1
Case Value2
Case Subtitle
}

When you need to point to an enumeration value, use an enumeration name that begins with a dot (.):

Copy Code code as follows:

Swift
Let Cellstyle:uitableviewcellstyle =. Default

Swift also introduced the Ns_options macro option. The behavior of the option is similar to the introduced enumeration, and the option can also support some bit operations, such as &,| and ~. In Objective-c, you use an empty option to set the indicator constant to 0 (0). In Swift, there is no option to use the Nil representative.

Pointer

Swift avoids giving you direct access to pointers as much as possible. However, Swift also provides you with a variety of pointer types when you need to manipulate the memory directly. The following table uses type as the placeholder type name to represent the mapping of the syntax.
For parameters, use the following mappings:

C Syntax Swift Syntax
const void * Cconstvoidpointer
void * Cmutablevoidpointer
Const TYPE * Cconstpointer<type>
Type * Cmutablepointer<type>


For multiple-level pointers to return types, variables, and parameter types, use the following mappings:

C Syntax Swift Syntax
void * Copaquepointer
Type * Unsafepointer<type>


For class type, use the following mappings:

C Syntax Swift Syntax
Type * Const * Cconstpointer<type>
Type * __strong * Cmutablepointer<type>
Type * * Autoreleasingunsafepointer<type>

C variable Pointers

When a function is declared to accept the cmutablepointer<type> parameter, this function can accept any of the following types as arguments:

Nil, passing in as a null pointer
• A value of a cmutablepointer<type> type
• An operand is an input-output expression of the value of the type's left, which is passed as the memory address of this left value
• An input-output type[] value that is passed in as the starting pointer of an array, and its lifecycle is extended during this call

If you declare a function like this:

Copy Code code as follows:

Swift
Func Takesamutablepointer (x:cmutablepointer<float>) {/*...*/}

Then you can invoke this function in any of the following ways:

Copy Code code as follows:

Swift
var x:float = 0.0
var p:cmutablepointer<float> = Nil
var a:float[] = [1.0, 2.0, 3.0]

Takesamutablepointer (Nil)
Takesamutablepointer (P)
Takesamutablepointer (&x)
Takesamutablepointer (&a)

When a function is declared to use a cmutablevoidpointer parameter, the function accepts any type operand that is similar to the cmutablepointer<type>.

If you define a function like this:

Copy Code code as follows:

Swift
Func Takesamutablevoidpointer (x:cmutablevoidpointer) {/* ... */}

Then you can invoke this function in any of the following ways:

Copy Code code as follows:
Swift
var x:float = 0.0, Y:int = 0
var p:cmutablepointer<float> = nil, q:cmutablepointer<int> = nil
var a:float[] = [1.0, 2.0, 3.0], b:int = [1, 2, 3]

Takesamutablevoidpointer (Nil)
Takesamutablevoidpointer (P)
Takesamutablevoidpointer (q)
Takesamutablevoidpointer (&x)
Takesamutablevoidpointer (&y)
Takesamutablevoidpointer (&a)
Takesamutablevoidpointer (&B)

C constant pointer

When a function is declared to accept the cconstpointer<type> parameter, this function can accept any of the following types as arguments:

Nil, passing in as a null pointer
• a cmutablepointer<type>, Cmutablevoidpointer, Cconstpointer<type>, Cconstvoidpointer, Or, if necessary, convert to cconstpointer<type> autoreleasingunsafepointer<type> value
• An operand is an input-output expression of the value of the type's left, which is passed as the memory address of this left value
• A type[] array value that is passed in as the starting pointer of an array, and its lifecycle is extended during this call

Copy Code code as follows:

Swift
Func Takesaconstpointer (x:cconstpointer<float>) {/*...*/}

Then you can invoke this function in any of the following ways:

Copy Code code as follows:

Swift
var x:float = 0.0
var p:cconstpointer<float> = Nil

Takesaconstpointer (Nil)
Takesaconstpointer (P)
Takesaconstpointer (&x)
Takesaconstpointer ([1.0, 2.0, 3.0])

When a function is declared to use a cconstvoidpointer parameter, the function accepts any type operand that is similar to the cconstpointer<type>. If you define a function like this:

Copy Code code as follows:

Swift
Func Takesaconstvoidpointer (x:cconstvoidpointer) {/* ... */}

Then you can invoke this function in any of the following ways:

Copy Code code as follows:

Swift
var x:float = 0.0, Y:int = 0
var p:cconstpointer<float> = nil, q:cconstpointer<int> = nil

Takesaconstvoidpointer (Nil)
Takesaconstvoidpointer (P)
Takesaconstvoidpointer (q)
Takesaconstvoidpointer (&x)
Takesaconstvoidpointer (&y)
Takesaconstvoidpointer ([1.0, 2.0, 3.0])
Takesaconstvoidpointer ([1, 2, 3])

Automatically releasing unsafe pointers

When a function is declared to accept the autoreleasingunsafepointer<type> parameter, this function can accept any of the following types as arguments:

Nil, passing in as a null pointer
• A autoreleasingunsafepointer<type> value
• Its operands are original, copied to a temporary an input-output expression that does not have an owner's buffer, the address of the buffer is passed to the call, and when returned, the value in the buffer is loaded, saved, and reassigned to the operand.

Note: This list does not contain an array.

If you define a function like this:

Copy Code code as follows:

Swift
Func Takesanautoreleasingpointer (x:autoreleasingunsafepointer<nsdate?>) {/* ... */}


Then you can invoke this function in any of the following ways:

Copy Code code as follows:

Swift
var x:nsdate? = Nil
var p:autoreleasingunsafepointer<nsdate?> = Nil

Takesanautoreleasingpointer (Nil)
Takesanautoreleasingpointer (P)
Takesanautoreleasingpointer (&x)

Note: The C language function pointer is not introduced by Swift.

Global constants

Global constants defined in the C and Objective-c language source files are automatically compiled and made swift as global constants by Swift.

preprocessing directives

The Swift compiler does not contain a preprocessor. Instead, it takes full advantage of compile-time attributes, build configurations, and language features to accomplish the same function. Therefore, Swift did not introduce a preprocessing directive.

Simple macros

In C and objective-c, a macro constant defined by the #define directive that you typically use, in Swift, you can use global constants instead. For example: A global definition of #define fade_animation_duration 0.35, in Swift can use let fade_animation_duration = 0.35来 better presentation. Because simple macros that define constants are directly mapped to Swift's global volume, the SWIFT compiler automatically introduces simple macros defined in a C or objective-c source file.

Complex macros

The complex macros used in C and objective-c do not have a corresponding definition in Swift. Complex macros are macros that are not used to define constants, but are used to define macros that contain parentheses () and functions. Your use of complex macros in C and objective-c is used to avoid the restriction of type checking and duplication of work for the same code. However, macros can also create bugs and refactoring difficulties. In Swift you can use functions and generics directly to achieve the same effect. As a result, complex macros defined in the C and objective-c source files are not available in Swift.

Compiling configuration

The Swift code and the OBJECTIVE-C code are conditionally compiled in different ways. The Swift code can be conditionally compiled based on the evaluation of the build configuration. The build configuration includes true and false literals, command line flags, and platform test functions in the following table. You can specify command line flags using-D <#Flag#>.

function Valid Parameters
OS () OS X, IOS
Arch () x86_64, ARM, arm64, i386

Note: The arch (ARM) build configuration does not return true for the 64-bit ARM device, and the Arch (i386) build configuration returns True when the code runs in the 32-bit iOS emulator.

A simple conditional compilation requires the following code format:

Copy Code code as follows:

#if build Configuration
Statements
#else
Statements
#endif

A statements, declared by 0 or more valid Swift statements, can include expressions, statements, and control flow statements. You can add additional build configuration requirements, conditional compilation instructions with && and | | Operators as well! operator, add a conditional control block with #elseif:

Copy Code code as follows:

#if build configuration &&!build Configuration
Statements
#elseif build Configuration
Statements
#else
Statements
#endif

Contrary to the conditional compilation of the C language compiler, Swift conditional compilation statements must be entirely self-contained and syntactically valid blocks of code. This is because Swift code, even if it is not compiled, is checked for grammar.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.