Swift uses the data type tutorial in Cocoa _swift

Source: Internet
Author: User

As part of OBJECTIVE-C Interoperability (interoperability), Swift provides a fast and efficient way to handle cocoa data types.

Swift will automatically convert some objective-c types to Swift types and convert Swift types to objective-c types. There are also data types that are interoperable in objective-c and Swift. Those data types that can be converted or have a data type that is interoperable are called bridged data types. For example, in Swift, you can pass an array value to a method that requires a Nsarray object. You can also convert a bridged type and a copy of it. When you use the As transformation bridged type or those supplied by constants and variables, Swift bridges their data types.

Swift also provides a simple and convenient overlay method for connecting Foundation data types, and in the swift language that follows, you can feel the nature and unity in its syntax.

String

Swift is automatically converted in string type and NSString type. This means that where you can use the NSString object, you can replace it with a string that belongs to Swift, which also has the characteristics of their data types, string interpolation, A wider range of applications based on Swift's design APIs and NSString classes. Therefore, you almost no longer have to use the NSString class in your code. In fact, when Swift accesses the objective-c APIs, it replaces all nsstring types with the string type. When you use the Swift class in your objective-c code, the Access API replaces all string types with the NSString type.

To allow string conversions, simply access the foundation. For example, you call a method of capitalizedstring--a NSString class in a string of swift, and then Swift automatically converts a string to a NSString object and invokes the method. This method would even return a string of Swift because it was replaced at the time of the connection.

Copy Code code as follows:

Import Foundation
Let greeting = "Hello, world!"
Let capitalizedgreeting = greeting.capitalizedstring
capitalizedgreeting:string = Hello, world!

If you really need to use a NSString object, you can use a Swift string value and convert it. A string type can always be converted from a NSString object to a swift string value, so there is no need to use an optional type converter () as?). You can also create a NSString object in a string by defining constants and variables.

Copy Code code as follows:

Import Foundation
Let mystring:nsstring = "123"
If let IntegerValue = (myString as String). ToInt ()) {
println ("\ (myString) is the integer \ (integervalue)")
}

Localization

In Objective-c, a common nslocalizedstring class macro is used to locate a string. The macros for this collection include Nslocalizedstringfromtableinbundle and Nslocalizedstringwithdefaultvalue. In Swift, however, only one function can achieve the same function as the entire nslocalizedstring set, namely Nslocalizedstring (key:tableName:bundle:value:comment:). This nslocalizedstring function provides a default value for the Tablename,bundle and value parameters, respectively. You can use it to replace macros.

Digital

Swift automatically converts the determined number type int and float to nsnumber. Such a conversion allows you to create a nsnumber based on one of these types:

Copy Code code as follows:

Let n = 42
Let M:nsnumber = n

You can also pass a value of type int, such as passing to a parameter that requires a type of nsnumber. It's also worth noting that NSNumber can contain many different types, so you can't pass it to a single int value.

The types listed below are automatically converted to NSNumber:

Copy Code code as follows:
Int
UInt
Float
Double
Bool

Class Collection

Swift automatically converts the Nsarray and Nsdictionary classes to the equivalent classes in Swift. This means that you will benefit from Swift's powerful algorithms and unique syntax for handling collections-Foundation and Swift collection types that can be converted to each other.

Array

Swift will automatically convert between the array type and the Nsarray type. When you convert from an array of Swift to a Nsarray object, the converted array is an array of anyobject[] types. If an object is an instance of a objective-c or Swift class, or if the object can be converted to another type, then the object belongs to the Anyobject type object. You can convert any of the Nsarray objects into an array of Swift, because all Objective-c objects are anyobject types. Because of this, Swift's compilers will replace Nsarray classes with anyobject[when accessing Objective-c APIs.

When you convert a Nsarray object into an array of Swift, you can also convert the array coercion type to a specific type. Unlike converting from a Nsarray class to a anyobject[], converting an object from a Anyobject type to an explicit type does not guarantee success. Converting from anyobject[to sometype[] Returns a optional value, because the compiler does not know if the Anyobject object can be cast to a specific type until the runtime. For example, if you know that a swift array contains only an instance of the UIView class (or a subclass of a UIView Class), you can cast an array element of the Anyobject type to the UIView object. If the element in the swift array is not an object of type UIView at run time, then the conversion returns nil.

Copy Code code as follows:

Let Swiftyarray = Foundationarray as anyobject[]
If let Downcastedswiftarray = Swiftarray as? Uiview[] {
Downcastedswiftarray contains only UIView objects
}

You can also cast a Nsarray object to a specific type of swift array in the For loop:

Copy Code code as follows:

For aview:uiview! In Foundationarray {
Aview is of type UIView
}

Note: This conversion is a cast and generates an error message at run time if the conversion is unsuccessful.

When you convert from the swift array to the Nsarray object, the elements in the swift array must belong to the Anyobject. For example, a Swift array of int[] types contains elements of an int structure. The int type is not an instance of a class, but because the int type is converted to the NSNumber class, the int type belongs to the Anyobject type. Therefore, you can convert a int[-type Swift array to a Nsarray object. If an element in the Swift array does not belong to the Anyobject type, an error occurs at run time.

You can also create a Nsarray object from the Swift array. When you define a constant or variable as an Nsarray object and assign an array to it as an instance variable, Swift will create the Nsarray object instead of the swift array.

Copy Code code as follows:

Let Schoolsupplies:nsarray = ["Pencil", "Eraser", "Notebkko"]
Schoolsupplies is a Nsarray object containing NSString objects

In the example above, the Swift array contains three string strings. Because of the conversion from the string type to the NSString class, the literal amount of the array is converted to a Nsarray object and successfully assigned to the Schoolsupplies variable.

When you use the Swift class or protocol in OBJECTIVE-C code, the Access API replaces all types of swift arrays as Nsarray. If you pass a Nsarray object to Swift's API and require an array element to be a new type, the runtime generates an error. If the swift API returns an array of Swift that cannot be converted to the Nsarray type, the error also occurs.

Foundation Data type

Swift also provides a simple and convenient overlay method to connect the data types defined in the Foundation framework. Using the overlay method in Nssize and Nspoint, in the remaining Swift language, you can feel the nature and unity in its syntax. For example, you can create a nssize type structure using the following syntax:

Copy Code code as follows:

Let size = Nssize (width:20, height:40)

The overlay method also allows you to invoke Foundation's structural functions in a natural way.

Copy Code code as follows:

Let rect = Nsrect (x:50, y:50, width:100, height:100)
Let width = rect.width//equivalent of nswidth (rect)
Let MaxX = rect.maxy//equivalent of Nsmaxy (rect)

Swift can convert Nsuinteger and nsinteger to type int. These types will become int types in the Foundation APIs. int is often used as consistent in Swift, and the UINT type is always available when you require an unsigned integer type.

Foundation function

In Swift, NSLog can output information at the system console. You can use this function in the same way as the syntax format used in OBJECTIVE-C.

Copy Code code as follows:

NSLog ("%.7f", pi)//Logs "3.1415927" to the console

At the same time, Swift also provides output functions like print and println. The character interpolation mechanism, which is attributed to Swift, makes these functions simple, rough, and efficient. These functions do not output information in the system console, but are available when the call is needed.

There is no longer a nsassert function in Swift, instead of an assert function.

Core Foundation

The Core Foundation type in Swift is a mature class. When memory management annotations occur, Swift automatically manages the memory of the core Foundation object, including the core Foundation object that you instantiate. In Swift, you are free to transform fundation and Core Foundation types. If you want to convert to a bridging Foundation type first, you can also bridge some toll-free bridged Core Foundation type to the Swift standard library type.

Redefining types

When Swift imports the Core Foundation type, the compiler will remap the imported type name. The compiler removes ref from the end of each type name because all Swift classes belong to reference types, so suffixes are superfluous.

The Cftyperef type in the Core Foundation will remap the Anyobject type. So the cftyperef you used before, now it's time to replace Anyobject.

Memory Management Objects

In Swift, the Core Foundation object returned from the annotated APIs can be managed automatically-you no longer need to call your own cfretain,cfrelease, or the Cfautorelease function. If you return a Core Foundation object from your own C function and Objective-c method, you need to annotate the object with cf_returns_retained or cf_returns_not_retained. When these APIs are included in the Swift code, the compiler automatically invokes memory management at compile time. If you only invoke annotated APIs that do not return the Core Foundation object indirectly, you can now skip the remainder of this section. Otherwise, we continue to learn about unmanaged Core Foundation objects.

unmanaged objects

When Swift imports unannotated APIs, the compiler will not automatically host memory management of the returned Core Foundation objects. Swift closes these returned Core Foundation objects in a unmanaged<t> structure. Objects that return the Core Foundation indirectly are also unmanaged. For instance, here's a unannotated C function:

Copy Code code as follows:

Cfstringref stringbyaddingtwostrings (cfstringref string1, cfstringref string2)

Here's how Swift is imported:

Copy Code code as follows:

Func stringbyaddingtwostrings (cfstring!, cfstring!)-> unmanaged<cfstring>!

Assuming you receive an unmanaged object from the unannotated APIs, you must convert it to an object that can be managed in memory before using it. In this regard, Swift can help you with memory management without having to do it yourself. The,unmanaged<t> structure also provides two ways to convert an unmanaged object into a memory-managed object--takeunretainedvalue () method and a Takeretainedvalue () method. The two methods return the original, closed object type. You can choose which method is more appropriate depending on the unretained or retained object returned by the APIs you actually invoke.

For example, suppose there is a C function that does not release the Cfstring object until it returns a value. Before using this object, you use the Takeunretainedvalue () function to convert it to an object that can be managed by memory.

Copy Code code as follows:

Let Memorymanagedresult = Stringbyaddingtwostrings (str1, str2). Takeunretainedvalue ()
Memorymanagedresult is a memory managed cfstring

You can also use retain (), release (), and Autorelease () methods in an unmanaged object, but this practice is not worth recommending.

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.