IOS application development using swift

Source: Internet
Author: User

In Swift, you can directly use the APIS provided by Objective-C language (including the system framework and custom code), and use the classes and APIs provided by Swift in Objective-C, it can also use both Swift and Objective-C languages in a single project. The two languages can interwork and interact with each other.

Any Objective-C framework or C library (including all Objective-C system frameworks, such as Foundation, UIKit, SpriteKit, and public c library provided by the system) the module is directly imported into Swift for use in the Swift language.

For example, to use the Foundation framework, simply add the following input declaration statement at the top of the Swift file to use the Foundation framework:

Import Foundation

In this way, all the APIS contained in the Foundation framework, including NSDate, NSURL, NSMutableData, and all methods, attributes, and categories, can be directly used by the Swift file.

1. Integration with Objective-C language and framework

1.1 Object Instantiation

To use an Objective-C class in Swift, you can use the Swift syntax to call an initialization method of it for instantiation.

UITableView * myTableView = [[UITableViewalloc] initWithFrame: CGRectZerostyle: UITableViewStyleGrouped];

The above Objective-C object initialization method needs to be called in the Swift language.

Let myTableView: UITableView = UITableView (frame: CGRectZero, style:. Grouped)

Because the Swift language automatically processes the memory allocation of an instance, alloc is not required for memory allocation in the Swift language. In Objective-C, the init or initWith prefix indicated by the instance initialization method name is not required in the Swift initialization syntax, but the class name is used as the name of the Instance initialization method, follow the Objective-C language instance initialization method name initWith and use the word as the first parameter of the Swift initialization method.

In the Swift language, the object type in the initialization syntax of the instance can also be reduced (the UITableView in the above example), Swift can automatically and correctly infer its type, as shown below:

Let myTableView = UITableView (frame: CGRectZero, style:. Grouped)

To ensure consistency and simplicity, the Objective-C factory method is automatically mapped to the Swift language for convenient initialization when being imported to Swift. For example, in Objective-C, call a factory method as follows.

UIColor * color = [UIColorcolorWithRed: 0.5 green: 0.0 blue: 0.5 alpha: 1.0];

In Swift, you should call the following method:

Let color = UIColor (red: 0.5, green: 0.0, blue: 0.5, alpha: 1.0)

1.2 access to attributes and Methods

Use the dot syntax in Swift to access and set the attributes and call methods of the Objective-C object.

In Swift, you can use the dot syntax to directly access an attribute by using its name. For example:

MyTextField. textColor = UIColor. darkGrayColor ()

MyTextField. text = "Hello world"

For methods, the first part of the Objective-C method name is directly used as the method name in Swift, and other parameters used as the Swift method parameters are included in the parentheses of the method. For example, the following Objective-C method.

[MyTableViewinsertSubview: mySubviewatIndex: 2];

The following is a call in Swift.

MyTableView. insertSubview (mySubview, atIndex: 2)

The id type in Objective-C is mapped to the AnyObject type in the Swift language when it is imported into Swift.

Pointers in Objective-C are mapped to the optional type of the Swift language when they are imported into Swift.

1.3 extended functions

Added and extended functions using classes, structures, and enumerations defined in Objective-C language, including those defined in the system framework or defined by yourself.

If you use extensions to add attributes (including class and static attributes), the extended attributes must be calculated attributes. As shown in the following figure, a calculation attribute area is added for the CGRect class using the extension:

Extension CGRect {

Var area: CGFloat {

Return width * height

}

}

Let rect = CGRect (x: 0.0, y: 0.0, width: 10.0, height: 50.0)

Let area = rect. area

// Area: CGFloat = 500.0

Extensions can also be used to add protocol support for Objective-C classes. If the protocol is defined by Swift, you can add support for this Protocol for any structure or enumeration type (whether defined by Objective-C or Swift.

However, Extensions cannot be used to override attributes or methods of the Objective-C type.

1.4 block and Closure

The blocks in Objective-C are imported to Swift in the closed mode of Swift.

Void (^ completionBlock) (NSData *, NSError *) = ^ (NSData * data, NSError * error ){/*...*/}

The above Objective-C language-defined block needs to be used (converted to closed) after being imported to Swift ):

Let completionBlock: (NSData, NSError)-> Void = {data, errorin /*...*/}

Since the closure in Swift is compatible with the block in Objective-C, you can pass the closure (including the Swift function) to any Objective-C method that uses the block as the parameter.

1.5 inherit from and use the protocols in Objective-C

In Swift, you can define a Swift class that inherits from an Objective-C class, and you can also directly use the Objective-C language-Defined Protocol in Swift. The following defines a Swift subclass of the UIViewController class derived from the Objective-C framework UIKit.

Import UIKit

Class MySwiftViewController: UIViewController {

// Define the class

}

The following defines a Swift class MySwiftViewController using the UITableViewDelegate and UITableViewDataSource protocols in Objective-C.

Class MySwiftViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

// Define the class

}

Classes defined by Swift (including classes inherited from Objective-C) are always initialized using the Swift language initialization method, swift automatically converts Objective-C to the initialization method in Swift.

1.6 compatibility with Objective-C

When defining a Swift class derived from NSObject or other Objective-C classes, the Swift class is automatically compatible with Objective-C, and the Objective-C code can be used directly.

Note that in Objective-C, a subclass that inherits the Swift class cannot be defined.

If the Swift class is not derived from the Objective-C class, the Objective-C code cannot use it directly. If you want to enable the Swift class to be used by the Objective-C code, you need to use @ objc to identify it.

When a Swift API is used in Objective-C code, the compiler automatically performs a direct conversion operation. Swift APIs are converted to Objective-C.

For example, a function func playSong (name: String) in Swift is converted to the following format-(void) playSong :( NSString *) name in Objective-C language.

An Initialization Method of Swift, init (songName: String, artist: String), is converted to the following form of Objective-C:

-(Instancetype) initWithSongName :( NSString *) songName artist :( NSString *) artist.

In Swift, @ objc can also be used to specify another name that can be recognized and used by Objective-C. As follows:

@ Objc (Squirrel)

Class extends {

@ Objc (initWithName :)

Init (program metadata failed: String ){/*...*/}

@ Objc (hideNuts: inTree :)

Func functions have been passed into memory when there are too many threads (Int, please wait until there are too many threads: Please wait until there are too many threads ){/*...*/}

}

1.7. Bridge with the Cocoa Data Type

Swift can automatically switch between some Objective-C and Swift types, and there are also some types that can be replaced and used between Swift and Objective-C. Convertible or replaceable types are called Bridge types. For example, the Array type in Swift and the NSArray class in Objective-C, the String type in Swift, the NSString class in Objective-C, the Dictionary type in Swift, and the NSDictionary class in Objective-C, all are bridge-able types.

In Swift, NSString can be replaced by String anywhere, and the functions provided by both types can be used. For example, you can call the capitalizedString method provided by NSString on the String type of Swift.

To allow and use the bridge function in Swift, you only need to enter the Foundation framework. As follows:

Import Foundation

Let greeting = "hello, world! "

Let capitalizedGreeting = greeting. capitalizedString

// CapitalizedGreeting: String = Hello, World!

You can also create an NSString object like creating a String, as shown below:

Import Foundation

Let myString: NSString = "123"

If let integerValue = (myStringasString). toInt (){

Println ("\ (myString) is the integer \ (integerValue )")

}

Swift also automatically bridges the Int, Float, UInt, Double, Bool, and NSNumber types, therefore, you can use the Int, Float, UInt, Double, and Bool types to create an NSNumber object. A parameter of the Int, Float, UInt, Double, or Bool type can also be transferred to the required NSNumber parameter.

Let n = 42

Let m: NSNumber = n

Note: The NSNumber and NSUInteger types of Cocoa are both converted to the Int type of Swift.

When bridging an NSArray object into a Swift Array, the NSArray Array type must be compatible with AnyObject, and the result Array type must be AnyObject []. All Objective-C objects are compatible with the AnyObject type, so any type of NSArray objects can be converted to Swift arrays.

Similarly, if the elements in the Swift array are compatible with AnyObject, a Swift array can also be converted to an NSArray object. Otherwise, a runtime error will occur.

You can also create an NSArray object like creating a Swift array.

Let schoolSupplies: NSArray = ["penpencil", "Eraser", "Notebook"]

// SchoolSupplies is an NSArray object containing NSString objects

2. Interaction with C API

2.1 Basic C language type

Swift provides the same type as the basic type of C language. However, unless necessary, it is not recommended.

C Type 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 CLongLong

Unsigned long CUnsignedLongLong

Wchar_t CWideChar

Char16_t CChar16

Char32_t CChar32

Float CFloat

Double CDouble


2.2 C-style enumeration

The C-style enumeration marked with the NS_ENUM macro in the Objective-C language or the option marked with NS_OPTIONS is automatically converted to an enumeration in the Swift format when importing Swift.

OBJECTIVE-C

Typedef NS_ENUM (NSInteger, UITableViewCellStyle ){

UITableViewCellStyleDefault,

UITableViewCellStyleValue1,

UITableViewCellStyleValue2,

UITableViewCellStyleSubtitle

};

Is converted to the following Swift enumeration form.

SWIFT

EnumUITableViewCellStyle: Int {

CaseDefault

CaseValue1

CaseValue2

CaseSubtitle

}

2.3 pointer

Swift does not directly use pointers, but it also provides several types of pointers for direct access to memory.

The pointer as a parameter has the following ing relationships:

C Syntax Swift Syntax

Const void * CConstVoidPointer

Void * CMutableVoidPointer

Const Type * CConstPointer

Type * CMutablePointer

Pointers of the return type, variables, and parameter types have the following ing relationships:

C Syntax Swift Syntax

Void * COpaquePointer

Type * UnsafePointer

The class pointer has the following ing relationships:

C Syntax Swift Syntax

Type * const * CConstPointer

Type * _ strong * CMutablePointer

Type ** AutoreleasingUnsafePointer

The preceding Type is a placeholder Type, which can represent any Type.

2.4 macro definition and Conditional compilation

The basic constant defined by # define in C language is automatically converted into a global variable in Swift by the Swift compiler when being imported into Swift. However, complex macro definitions cannot be converted by Swift.

Swift code also supports Conditional compilation, as shown below:

# If build configuration &&! Build configuration

Statements

# Elseif build configuration

Statements

# Else

Statements

# Endif

3. Integration with Interface Builder

In Swift, @ IBOutlet @ IBAction is also used to define the Outlets attribute and Actions action to connect code with user interface objects. As shown below, the MyViewController class declares an outlet attribute connected to the user interface object, an outlet attribute array, and an action.

Class MyViewController: UIViewController {

@ IBOutlet var button: UIButton

@ IBOutlet var textFields: UITextField []

@ IBAction func buttonTapped (AnyObject ){

Println ("button tapped! ")

}

}

When @ IBOutlet is used to declare an outlet, Swift automatically converts it to an expanded option type with a weak reference implicit type and assigns its initial value nil.

Swift uses the @ IBDesignable attribute to declare a specific view object that can be used in Interface Builder, and uses the @ IBInspectable attribute to declare a view attribute that can be edited in inspector of Interface Builder. A view and related attributes are declared as follows:

@ IBDesignable

Class MyCustomView: UIView {

@ IBInspectable var textColor: UIColor

@ IBInspectable var iconHeight: CGFloat

/*...*/

}

4. Use Swift and Objective-C language in combination

In a separate project, the Objective-C and Swif files can also be included.

To enable a group of Objective-C files to be used by Swif files in the same application project, you need to use Xcode to create an Objective-C bridging header file, and import each Objective-C header file used by Swift in the bridging header file. The name of the bridge header file is the product name with the-Bridging-Header.h suffix.

OBJECTIVE-C header files

# Import "XYZCustomCell. h"

# Import "XYZCustomView. h"

# Import "XYZCustomViewController. h"

The features defined in the Objective-C header file added to the Objective-C bridging header file will be automatically used by Swift files of the same project.

When Objective-C code needs to use Swift code in the same application project, Xcode automatically generates an Objective-C header file containing all the Swift file interface declarations in the same project, add "-Swift. h.

Then, import the header file in the following format in the Objective-C file to use Swift code.

# Import ProductModuleName-Swift.h"

Then, the Objective-C file will be able to use the functions exposed in all Swift files in the same project.

To reference a Swift class in an Objective-C header file, you must use @ class to declare the class before reference. As follows:


OBJECTIVE-C

// MyObjcClass. h

@ Class MySwiftClass;

@ Interface MyObjcClass: NSObject

-(MySwiftClass *) return SwiftObject;

/*...*/

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.