Author: Donggua, iOS developer, head of the official technical account “Yigua Technology”, currently working in the iOS infrastructure group of Tiktok bytedance.

Session:developer.apple.com/videos/play…

primers

It’s been 10 years since Chris Lattner started designing Swift, but what has Swift updated this year? Let’s take a look.

Every year’s “What’s New in… Series have many essentials. Swift, the evolving language, is sure to shine again this year, bringing even more pleasing new features to us developers. In this Session, not all of the evolution details of Swift 5.3 were available, but the most important features of Swift 5.3 were put together to give us a better idea of the new Swift.

Without further ado, turn to the text.

Contents of this article

Apple developer ecosystem overview

As the ABI becomes more stable, Swift 5 will see more and more powerful apis being opened up. SwiftUI is one of them. Over the past year, Swift has put a lot of effort into the development of both the top and bottom Apple apis to build a more complete Apple development ecosystem.

Of course, more and more powerful functions are also inseparable from the development tool Xcode, Swift Package Manager Package Manager, which is also an important part of Apple’s development ecosystem. At the same time, as a cross-platform Swift language and SwiftUI this cross-platform application scheme is also quite important.

So in this “What’s New in Swift” post, we cover each of the features in Swift’s two latest releases around four themes:

  • Swift’s Runtime Performance
  • Developer Experience
  • Multi-platform Solution
  • Languages and Libraries

This will give you an overview of the most important information about the new Swift.

Swift operation efficiency was improved

Code Size

Apple officially keeps an eye on the size of __text in the Swift project artifacts. The following vertical axis is in units of the Size of the __text **Section generated by objective-C code, ** the Swift version of the horizontal axis, The value is Val=SSwiftSObjCVal=\frac{S_{Swift}}{S_{ObjC}}Val=SObjCSSwift. From Swift 4 to version 5.3, the initial 2.3 times has been optimized to 1.5 times.

But why does Swift need so much Code Size? The official explanation is that these differences are unavoidable because Swift has some “security” related features that require a certain amount of code implementation in the generated product, thus increasing the Size of the __text Section.

Of course, different sizes of apps will produce differentiated optimization results. For example, in Thomas Ricouard’s open source project MovieSwiftUI, the result of compiling with Xcode 12 is 43% lower than __text with version 11.

Optimized Dirty Memory usage

For a typical desktop operating system, clean memory can be thought of as the part that can Page Out. Due to the lack of memory swapping, clean memory for iOS refers to memory that can be recreated. It consists of the following categories:

  • Binary executable file for app
  • _DATA_CONST segment in the framework
  • Memory for file mapping
  • Memory that has not been written to

To summarize, dirty memory refers to memory that cannot be reclaimed by the system. What are the optimizations for dirty memory in Swift 5.3?

Let’s take the following Mountain Model and its corresponding array and their Memory Layout as an example. Suppose we now have code for the Mountain Model:

/ / the Model file
@interface Mountain: NSObject
{
	NSUUID *uuid;
	NSString *name;
	float *height;
}
@end

// Other references to Model codes
NSArray<Mountain*> *mountains = loadMountains();
Copy the code

We know that NSArray in Objective-C stores Pointers to the corresponding elements, and every non-basic type of object is stored as a pointer. However, due to Tagged Pointer technology, we know that some NSStrings are less than 8 bytes short and do not need to use Pointers to store objects, thus achieving slight optimization.

In Swift, however, we observed that the maximum value stored directly (optimized like Tagged Pointer) was reduced to 16 bytes, 15 bit length groups for more scenarios. In addition, arrays in Swift store values directly, eliminating the need to access many of them through Pointers.

Therefore, the Memory Layout of Mountain Model in Objective-C and Swift will have the following comparison:

Here we used a demo with 400 Model objects and tested heap memory usage. You can see that Swift 5.3 has been optimized to 13\ FRAc {1}{3}31 under the original Objective-C.

These optimizations, while they may feel trivial on current devices and systems, have significant experience benefits on older devices and systems.

The Swift standard library sinks

This sink is relative to Foundation, and the Swift Standard Library now exists as a Foundation dependency. The Swift API for Foundation will be gradually improved in future installments, and methods that are only accessible through C and Objective-C will also be migrated.

Developer Experience

Diagnostic strategy

In the new version of Swift Compiler, the new diagnostic policy schema has been updated to optimize the prompt for problem paths. Two optimizations mentioned in Session:

  1. Use a new strategy to locate code problems;
  2. More accurate prompt and more feasible prompt scheme;

The compiler also logs more information when diagnosing a problem. The optimization details can be found at Swift.org: New Diagnostic Architecture Overview.

Code completion

As you can see in this example, with an empty dictionary, the compiler can infer the value of a ternary expression.

Another scenario is completion of dynamic properties, such as using KeyPath as a pass-through parameter within a method:

In addition to stronger completion capabilities, Xcode 12 also has significant speed improvements. In some scenarios (note this sentence), performance is up to 15 times better than Xcode 11.5!

Code indentation

There are also significant improvements in indentation in the new Xcode, which have been incorporated into the open source SourceKit. The modification of indentation has the following aspects:

  1. Chained method calls;
  2. Call parameters;
  3. Progenitor element;
  4. Collection elements that span multiple rows;
  5. Multi-line conditional statement (if.guardwhile);

Here’s an example from the MovieSwiftUI project to illustrate the improved indentation style of the new version of the chain call:

debugging

First we know that Swift imports apis from Objective-C code via Modules in Clang to parse related type and variable information. In this process, LLDB needs to import all Swift Modules and Clang Modules visible in the current debug context.

Although these Module files have a lot of type description information, because LLDB carries full environment information for the entire application and for all dynamic libraries, importing Clang Modules will fail due to “not implemented at compile time.”

To counter this, the new LLDB imports C and Objective-C types from DWARF debugging information into Swift as a backstop. This improves debugging stability for instance objects such as Variable View and Expression Evaluator in Xcode.

Swift Platform Compatibility

Swift’s official distribution also supports multiple platforms, including:

  • Apple systems;
  • Ubuntu 16.04, 18.04, 20.04;
  • CentOS 8;
  • Amazon Linux 2;
  • Windows (Coming Soon, Swift 5.3)

Swift will be used in more interesting scenarios due to its compatibility with multiple operating system environments. AWS Lambda service is one of them.

Serverless Functions Services are a convenient way to quickly implement server-side Functions. For mobile development, we don’t have to worry about a lot of operations and back-end knowledge. For now, it’s easy to do Serverless development using the open source Swift AWS Runtime service.

We can quickly launch a service using these three simple lines of code and Amazon’s AWS Lambda service:

New language features

Swift 5.3 has a host of new features:

  • SE-0249: Key Path Expressions as Functions
  • SE-0253: Callable values of user-defined nominal types
  • SE-0263: Add a String Initializer with Access to Uninitialized Storage
  • SE-0264: Standard Library Preview Package
  • SE-0266: Synthesized comparable conformance for enum types
  • SE – 0267 –where clauses on contextually generic declarations
  • SE-0268: Refined didSet semantics
  • SE-0269: Increase availability of implicit self in @escaping closures when reference cycles are unlikely to occur
  • SE-0270: Add Collection Operations on Noncontiguous Elements
  • SE-0276: Multi-Pattern Catch Clauses
  • SE-0277: Float16
  • SE-0279: Multiple trailing closures
  • SE-0280: Enum cases as protocol witnesses
  • SE-0281: @main: Type-Based Program Entry Points

Let’s analyze some representative features and talk about them in detail:

Se-0279: Multi-tail closure

In previous versions of Swift, trailing closures allowed only the last parameter. The new version allows multiple trailing closures, taking the animation of a UIView as an example:

UIView.animate(withDuration: 0.3) {
	self.view.alpha = 0
} completion: { _ in 
	self.view.removeFromSuperview()
}
Copy the code

This syntax of multiple trailing closures also works well for DSLS. Here’s an example of SwiftUI:

Use the syntactic sugar of multiple tail closures to make the chain writing more natural and smooth.

Se-0249: Key Path is functionalized

KeyPath was introduced in Swift 4.1. You can use it as a function in the new version, as shown in the previous code completion tip.

In this example, instead of a cumbersome closure, we use a Key Path to access the shoeSize property of each element.

This syntax is also very similar to the to_proc & Symbol syntax in Ruby, where we can:

# Ruby
contacts.chunked(&:showSize)

// Swift
contacts.chunked(by: \.shoeSize)
Copy the code

Which language do you prefer?

SE-0281: @mainProgram entrance

In previous versions of Swift, @uiApplicationMain was used to tell the compiler to implicitly generate main. Swift to run the application. In Swift 5.3, Apple has extended this feature.

For example, we can use the @main modifier keyword to describe the entry point on the command line:

Se-0269: Implicit in closureself

In closures, we declare self explicitly and access attributes via self dot, but the new version adds an implicit self to a structure or enumeration inside a closure. Here’s an example from SwiftUI:

Se-0276: Multi-mode capture

In previous Swift versions, try… catch… Statement In a production environment, the actual code causes some redundancy. For example, in the case of multiple Error types, it is often necessary to add switch in the catch clause… case… Statement to further judge:

In Swift 5.3, Apple extended try… catch… Syntax, so that its subclauses have the judgment function of switch statements, thus avoiding the occurrence of nested statements.

Enum Enhancements

1. Compare

In Swift 5.3, comparisons are supported by having an enum follow Comparable.

2. The enumerationcasesCan be used as protocol witnesses

In the old Version of Swift, suppose we had a scenario:

/ / DecodingError protocol
protocol DecodingError {
  static var fileCorrupted: Self { get }
  static func keyNotFound(_ key: String) -> Self
}

// We need two cases in JSONDecodingError
// fileCorrupted and keyNotFound, and follow DecodingError
// However, since both protocols must be written in method form, it is necessary to repeat them
// Even if the call syntax expression is the same
enum JSONDecodingError: DecodingError {
  case _fileCorrupted
  case _keyNotFound(_ key: String)
  static var fileCorrupted: Self { return ._fileCorrupted }
  static func keyNotFound(_ key: String) -> Self { return ._keyNotFound(key) }
}
Copy the code

For this scenario, Swift 5.3 introduced se-0280: Enum Cases as protocol Promo Feature. Now our code only needs to be simplified as follows:

Embedded DSL Enhancements

Swift 5.3 continues to enhance the syntax of DSLS (in SwiftUI) and now supports some complex conditional statement structures such as Switch… case… And if the let… And so on.

Another point to note is that in Swift 5.3, Builder attributes are no longer explicitly declared.

library

SDK – Float16

Float16 is the new IEEE 754 standard floating-point format for Swift 5.3. Float16 takes up only two bytes of memory, whereas single-precision floating-point numbers take up four bytes. Because it is only half the size, it can hold twice as much in SIMD registers or memory pages, which typically doubles performance on supported hardware.

Note, however, that as a smaller data type, its accuracy and scope are also more limited.

SDK – Apple Archive

Apple Archive is a new lossless Archive Archive from Apple. AppleArchive provides fast compression and has the following features:

  • Multi-core multi-thread processing, faster;
  • The ability to carry all the attributes of a File and use the Apple File System (APFS) feature when appropriate, for example:filesystem compression,full clonesorsparse files;
  • Flexible coding format, support error correction, archiving, writing summaries and other functions;
  • The API supports in-memory archive processing, stream access;

It is worth noting that are mentioned in the official Session to ArchiveByteStream. WithFileStream () the construction method using the Apple Swift System is a new library.

Swift System provides a more modern, easy-to-use System call interface API and a more general type of System underlying API such as Apple Archive. But after a translator Google, still did not find this library information, you can pay attention to later.

SDK – OSLog

In Swift 5.3, Apple made OSLog faster with compiler optimizations and added string interpolation and formatting capabilities. Perhaps this version of OSLog is your best chance to replace the print method.

Of course, if you want to learn more about OSLog, check out Session 10168 – Explore Logging in Swift.

Packages – Swift Numerics

Swift Numerics is a library for mathematical/scientific computations, covering almost all basic mathematical functions (e.g. sine and logarithm), as well as complex number computations.

This library makes up for Swift’s lack of mathematical expertise. If you are interested in this Package, check out Swift Numerics on the official website.

Packages – Swift ArgumentParser

Swift ArgumentParser is also an open source Swift library for command-line argument parsing.

Unlike other CLI Argument Parsers, the official Swift ArgumentParser follows the following design principles:

  • Friendly to command line prompts and help, and provides a best practice for writing;
  • Support simple one-time script commands, support complex nested multiple subcommands, and provide good help information;
  • Eliminates the problem of parsing parameters and reduces the probability of errors through Swift encapsulation.

Of course, if you’re interested in this Package, check out Announcing ArgumentParser on the official website.

Packages – Swift StandardLibraryPreview

This Package is used to provide a pre-release version of the Swift standard library that you can introduce and pre-experience through Swift Package Manager.

This is one of the official enhancements to the Swift Evolution process that have been announced. After the Preview version is released, Feature review can be carried out with the feedback of the community before the official version is released, so as to decide whether to keep or reject the new Feature.

Of course, if you want to learn more about StandardLibraryPreview Package, you can visit the StandardLibraryPreview Package website.

conclusion

This year is already the sixth year that Apple has made efforts in Swift. Given the current iOS development ecosystem, Swift has become a trend for us iOS developers, and learning is inevitable. With the Swift ecosystem, we can actually move the technology stack horizontally to do more interesting things.

Limited welfare

This article is from WWDC20 Inside Reference. I recommend this column here.

The “WWDC Insider reference” series was initiated by the veteran Driver Weekly, Knowledge Collection and SwiftGG technology organizations. We’ve been doing it for a couple of years, and it’s been good. It is mainly for the annual WWDC content, do a selection, and call on a group of front-line Internet iOS developers, combined with their actual development experience, Apple documents and video content to do a second creation.

There are 213 sessions this year. WWDC20 Insider selected 135 of these sessions, and the column has now produced 97 articles. It is on sale now, only 29.9 yuan, very discount.

See article also not enough friends, to subscribe to the WWDC20 inside ~ https://xiaozhuanlan.com/wwdc20 to continue reading

Pay attention to our

We launched LSJCoiding, a weekly newsletter for veteran drivers, which is called a welcome update to each issue.