Swift USES the data types tutorial in Cocoa

  • 2020-05-07 20:31:23
  • OfStack

As part of Objective-C interoperability, Swift provides a quick and efficient way to handle Cocoa data types.

Swift automatically converts some Objective-C types to Swift types and Swift types to Objective-C types. There are also some interoperable data types in Objective-C and Swift. Those data types that are convertible or interoperable are called bridged data types. For example, in Swift, you can pass an Array value to a method that requires an NSArray object. You can also convert 1 bridged type and its copy. When you use as to convert bridged types or those provided by constants and variables, Swift Bridges their data types.

Swift also provides a simple and convenient overlay method to connect Foundation's data types. In the later Swift language, you can feel nature and unification in its syntax.

string

Swift is automatically converted between String type and NSString type. This means that where NSString objects can be used, you can replace them with an String type belonging to Swift, which will have the characteristics of their data types, interpolation of String types, APIs based on Swift design, and a wider range of NSString classes. As a result, you almost never have to use the NSString class in your code anymore. In fact, when Swift is plugged into Objective-C APIs, it replaces all NSString types with String types. When you use the Swift class in your Objective-C code, the accessed API replaces all String types with NSString types.

To allow string conversion, simply access Foundation. For example, you call capitalizedString-- a method of NSString class -- in a string of Swift, after which Swift automatically converts String to an NSString object and calls the method. This method will even return 1 String type of Swift, because it was replaced on access.


import Foundation
let greeting = "hello, world!"
let capitalizedGreeting = greeting.capitalizedString
// capitalizedGreeting: String = Hello, World!

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


import Foundation
let myString: NSString = "123"
if let integerValue = (myString as String).toInt()){
    println("\(myString) is the integer \(integerValue)")
}

localization

In Objective-C, macros of the NSLocalizedString class are often used to locate a string. Macros for this collection include NSLocalizedStringFromTableInBundle and NSLocalizedStringWithDefaultValue. In Swift, only one function can be achieved with the function of the whole NSLocalizedString set 1 sample, namely NSLocalizedString (key: tableName: bundle: value: comment:). The NSLocalizedString function provides a default value for the tableName, bundle and value parameters, respectively. You can replace macros with it.

digital

Swift automatically converts the identified numeric types Int and Float to NSNumber. This conversion allows you to create an NSNumber based on one of these types:


let n = 42
let m: NSNumber = n

You can also pass a value of type Int, for example, to a parameter of type NSNumber. It is also important to note that NSNumber can contain many different types, so you cannot pass it to one Int value of a single 1.

The following types are automatically converted to NSNumber:

Int
UInt
Float
Double
Bool

class collection

Swift automatically converts NSArray and NSDictionary classes to their Swift equivalents. This means that you will benefit from Swift's powerful algorithm and unique syntax for handling collections -- the interconvertible Foundation and Swift collection types.

array

Swift is automatically converted between Array type and NSArray type. When you convert from an Swift array to an NSArray object, the converted array is an AnyObject[] array. If an object is an instance of the Objective-C or Swift classes, or if the object can be converted to another type, then the object is of type AnyObject. You can convert any 1NSArray object into an Swift array, because all Objective-C objects are of type AnyObject. Because of this, the compiler for Swift replaces the NSArray class with AnyObject[] when accessing Objective-C APIs.

When you convert an NSArray object to an Swift array, you can also cast an array to a specific type. Unlike converting from the NSArray class to AnyObject[], converting from an object of the AnyObject type to an explicit type does not guarantee success. Since the compiler does not know until runtime whether an AnyObject object can be cast to a particular type, converting from AnyObject[] to SomeType[] returns a value of optional. For example, if you know that an Swift array contains only instances of the UIView class (or a subclass of the UIView class), you can cast an AnyObject array element to an UIView object. If the element in the Swift array is not an object of type UIView at run time, the transform returns nil.


let swiftyArray = foundationArray as AnyObject[]
if let downcastedSwiftArray = swiftArray as? UIView[] {
    // downcastedSwiftArray contains only UIView objects
}

You can also cast NSArray objects directionally into Swift arrays of a specific type in the for loop:


for aView: UIView! in foundationArray {
     // aView is of type UIView
}

Note: this conversion is a cast and will generate an error message at run time if the conversion is unsuccessful.

When you convert from an Swift array to an NSArray object, the elements in the Swift array must belong to AnyObject. For example, an Swift array of type Int[] contains elements of the Int structure. The Int type is not an instance of a class, but since the Int type is converted to the NSNumber class, the Int type is of the AnyObject type. Therefore, you can convert an Swift array of type Int[] into an NSArray object. If an element in an Swift array is not of type AnyObject, an error occurs at run time.

You can also create an 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 an NSArray object instead of an Swift array.


let schoolSupplies: NSArray = ["Pencil", "Eraser", "Notebkko"]
// schoolSupplies is an NSArray object containing NSString objects

In the above example, the Swift array contains three String strings. Because of the conversion from String type to NSString class, the array literal is converted to an NSArray object and successfully assigned to the schoolSupplies variable.

When you use the Swift class or protocol in the Objective-C code, the accessed API replaces the Swift array of all types with NSArray. If you pass an NSArray object to API of Swift and require the array element to be of a new type, an error occurs at runtime. If Swift API returns an Swift array that cannot be converted to NSArray, an error occurs.

Foundation data type

Swift also provides a simple and convenient override method to connect data types defined in the Foundation framework. Using the override method in NSSize and NSPoint, in the rest of the Swift language, you can feel nature and unity in its syntax. For example, you can create a structure of type NSSize using the following syntax:


let size = NSSize(width: 20, height: 40)

The override method also allows you to call Foundation's structure functions in a natural way.


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 converts NSUInteger and NSInteger to Int types. These types all change to Int in Foundation APIs. In Swift Int is often used for as much coherence as possible, and UInt is always available when you ask for an unsigned integer type.

Foundation function

In Swift, NSLog outputs information at the system console. You can use this function as in the syntax format used in Objective-C.


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

Also, Swift provides output functions like print and println. Mostly due to Swift's character interpolation mechanism, these functions are simple, rough, and multiefficient. These functions do not output information in the system console, but are available when called.

The NSAssert function no longer exists in Swift, but is replaced by the assert function.

Core Foundation

The Core Foundation type in Swift is a mature class. When memory management comments appear, Swift automatically manages the memory of Core Foundation objects, including the Core Foundation objects you instantiated. In Swift, you are free to switch between Fundation and Core Foundation types. If you want to convert to the bridge Foundation type first, you can also bridge 1 toll-free bridged Core Core Foundation standard library type.

redefines the type

When Swift imports Core Foundation type, the compiler remaps the imported type name. The compiler removes Ref from the end of each type name because all Swift classes are of the reference type and therefore the suffix is redundant.

The CFTypeRef type in Core Foundation remaps the Anyobject type. So instead of CFTypeRef, it's time to switch to AnyObject.

memory management object

In Swift, the Core Foundation object returned from annotated APIs automatically manages memory -- you no longer need to call your CFRetain, CFRelease, or CFAutorelease functions. If you return an Core Foundation object from your C function and Objective-C method, you need to annotate the object with CF_RETURNS_RETAINED or CF_RETURNS_NOT_RETAINED. When APIs is included in the Swift code, the compiler automatically calls memory management at compile time. If you only call annotated APIs objects that do not return Core Foundation objects indirectly, you can now skip the rest of this section. Otherwise, let's move on to unmanaged Core Foundation objects.

unmanaged object

When Swift imports APIs of unannotated, the compiler will not automatically host the returned Core Foundation object in memory management. Swift closes these returned Core Foundation objects in one Unmanaged < T > In the structure. Objects that return Core Foundation indirectly are also unmanaged. For example, here is the C function of unannotated:


CFStringRef StringByAddingTwoStrings(CFStringRef string1, CFStringRef string2)

Here's how Swift was imported:


func StringByAddingTwoStrings(CFString!, CFString!) -> Unmanaged<CFString>!

Suppose you receive an unmanaged object from unannotated APIs. Before you can use it, you must convert it to a memory-managed object. In this respect, Swift can help you with memory management without having to do it yourself. At the same time, Unmanaged < T > The structure also provides two methods to convert an unmanaged object into a memory-manageable object -- the takeUnretainedValue() method and the takeRetainedValue() method. These two methods return the original, non-closed object type. You can choose which method is more appropriate, based on the unretained or retained object returned by the APIs you actually called.

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


let memoryManagedResult = StringByAddingTwoStrings(str1, str2).takeUnretainedValue()
// memoryManagedResult is a memory managed CFString

You can also use the retain(), release(), and autorelease() methods in 1 unmanaged object, but this is not recommended.


Related articles: