Edit | orange

New retail product | alibaba tao technology

Apple’s WWDC20 developer conference was streamed live from Apple Park at 1am on June 23rd as a keynote address.

Apple released more than 100 videos for developers today, covering Swift/SwiftUI, App Clips, Widgets, Privacy & Security, and more.

What are some new discoveries and new thoughts for developers and programmers?

Tao department technical client team, will bring you a series of inspiration behind the new system, welcome to exchange and discuss.

preface

SwiftUI is a new generation of declarative layout engine of Apple Platform launched by Apple Inc. in 2019. Last year, THE author upgraded the Beta and tried the whole family at the first time, and quickly launched the internal APP based on SwiftUI in a short time. I have also shared several articles about SwiftUI, but SwiftUI 1.0 is almost not used by any company in the official launch of the main APP. Apis are abandoned between Beta versions, UI styles are often incompatible, and large list performance is poor. “SwiftUI” was also called a Toy Framewrok.

With the release of WWDC 20 features and introductory videos, it’s clear that SwiftUI has reached its first year and has grown into a layout engine for the new era.

Here are some of the major changes and core strengths of SwiftUI.

PS: Readers are required to be familiar with Swift and SwiftUI 1.0.

SwiftUI Apps

Apple has been working on unifying the Apple Platform in recent years, from iPad multi-tasking and multi-window in recent years, to Mac Catalyst, and this year further directly launched Apple Silicon chip is truly unified from the hardware (VOICE: The cross-platform stuff you play with in software is all gizmos, hardware is king).

Rosetta2 Universal2 is also available to help developers migrate to the new platform at virtually no cost. However, as a software engineer, we should pay more attention to the changes of software ecology. Let’s start with what happens when you create your APP

You can see that new projects are created with a new set of templates based on the SwiftUI App Lifecycle cross-platform project. The code has also changed from UI/NS HostViewController to declarative description based on APP. Here is the before and after code.

Before

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let contentView = ContentView()
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }
}
Copy the code

After

import SwiftUI 
@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
Copy the code

In the command, @main is the Attribute added in Swift 5.1 to mark the entry point of the application. For more information, see SE-0281-main-attribute.md

At first glance it may seem that only the code has been streamlined. Many would argue that this is less concise than the main() => runApp(MyApp()) of Flutter; .

But the most important change is that this is the first cross-platform code to run directly on different platforms without introducing any UIKit, APPKit, WatckKit, etc Framewok. This means that we can move away from relying on traditional imperative UI programming for our UI layout systems. Reaching the actual platform is irrelevant.

SwiftUI abstracts the whole original platform differences into App and Scene. For a MAC /iOS/iPad/ Watch/TV /.. In terms of application, App represents the whole application, and Scene represents multiple Windows related to Window. Some devices have only one Scene, and some have multiple scenes. Although different OS do have differences, they reach the same semantic level.

Secondly, an APP without history baggage can start from a Swift APP Lifecycle style template without mixing with traditional UIKit/APPKit etc. This also means that apps can be completely Declared and state-driven.

Viusal Editing

Preview

In traditional DSL visual programming frameworks or platforms, such as Web Flutter, developers write the corresponding code and run it on the corresponding platform or debugging tool. SwiftUI, Apple’s most important software layer framework, is deeply integrated with Xcode, giving you a complete preview of your interface before it runs.

The powerful Preview allows you to go from writing DSLS to instantly Preview the effects, to modifying the effects directly from the Preview Canvas and generating code in the code editor. This is a huge improvement in the efficiency of daily development, especially when it comes to UI fine-tuning.

Xcode12 can preview the interface of multiple device environments simultaneously on Canvas or directly projected onto a real device.

For daily development, writing a UI interface often rely on the external network/disk/other data, to build properly, this also caused the UI development though is a relatively simple step of development, but also the most time consuming step, has the function of preview, can take out a lot of tedious work front, for r&d efficiency will have a very large.

Xcode Library

In writing a real project, a company’s APP UI contains hundreds of styles of View components. For a product with rich UI components, if a new requirement can be composed of existing components, the time to deliver the requirement can be greatly reduced.

However, for a large development team, it is difficult for a developer to know how many kinds of component libraries there are in the company, and even if he knows there is a certain component library, what he sees at the beginning is the code. Generally, he needs to write a certain Demo before he can sense with his eyes whether this component is what HE wants.

A more powerful tool is available in Xcode 12. A custom component that only complies with a LiberyContentProvider protocol is recognized by Xcode and can be recognized and previewed directly from Xcode like a system control. For a large team, this feature can greatly improve the efficiency of finding components and viewing component styles.

// Without trailing closure: uiView.animate (withDuration: 0.3, animations: {self.view.alpha = 0}, completion: {_inSelf. View. RemoveFromSuperview ()}) / / With the trailing closure UIView. The animate (withDuration: 0.3, animations: { self.view.alpha = 0 }) { _inself.view.removeFromSuperview() } // Multiple trailing closure arguments UIView.animate(withDuration: 3) {self.view.alpha = 0} completion: {_in
          self.view.removeFromSuperview()
        }
Copy the code

DSL

With the release of Swift5.3 and SwiftUI2.0, SwiftUI is also more expressive on DSL. Swift supports multiple tail closure syntax and Switch Case statement support in ViewBuilde.

Multiple Trailing Closures

While the discussion of multiple tail closures has been controversial in the community, Swift5.3 has finally embraced and implemented them. It can be somewhat confusing to use in the context of common imperative programming, but DSL in SwiftUI is also more declarative.

// Without trailing closure: uiView.animate (withDuration: 0.3, animations: {self.view.alpha = 0}, completion: {_inSelf. View. RemoveFromSuperview ()}) / / With the trailing closure UIView. The animate (withDuration: 0.3, animations: { self.view.alpha = 0 }) { _inself.view.removeFromSuperview() } // Multiple trailing closure arguments UIView.animate(withDuration: 3) {self.view.alpha = 0} completion: {_in
          self.view.removeFromSuperview()
        }
Copy the code

Switch Case Support

Switch Case syntax is also supported in SwiftUI’s ViewBuilder DSL.

      var body: some View {
            switch c {
            case .a:
                return Text("A")
            case .b:
                return Text("B")
            case .c:
                return Text("C")}}Copy the code

Data Flow

When writing UI code using traditional imperative programming, developers need to manually handle the dependencies between UIView and data. Whenever a UIView uses external data sources, it indicates that UIView is dependent on external data. When a data is changed, If the UIView state is accidentally not synchronized, a Bug can occur.

Dealing with simple dependencies is manageable, but in a real project, the dependencies between views can be very complex. Assuming that a view has only four states, it has 16 states combined, and the situation becomes even more complicated when the timing is different.

The complexity of human brain processing state is limited, once the complexity of state exceeds the complexity of human brain, a large number of bugs will be generated, and new bugs will be generated when the state is removed.

So how does SwiftUI solve this problem?

SwiftUI’s framework provides several core concepts:

  1. Unified body property, SwiftUI automatically generates a snapshot View based on the current state from the current App state set.

  2. Unified data flow primitives.

For details on how Data Flow in SwiftUI eliminates view and state inconsistencies, please refer to the document series I wrote last year entitled “In-depth Interpretation of the Things behind SwiftUI”.

The StateObject data flow primitive added to SwiftUI 2.0 this year allows SwiftUI to improve View reconstruction performance by avoiding duplicate ObservedObject creation when creating views repeatedly.

SceneStorage and APPStorgae make some persistent data simpler and semantic.

New Controls

As mentioned earlier, the new DSL syntax SwiftUI App Lifecycle and Xcode Library Preview are essentially new extensions to last year’s SwiftUI 1.0.

What really matters is the variety of new controls added this year, where you can see the entire declaration file grow from 10,769 lines to 20,564 lines by exporting Swift declarations from Xcode11.5 and Xcode12.0 beta versions.

About 87 structs and 16 protocols have been added. Only with these rich components can we build our APP better.

Large list component

There are similar large list components in any APP. For example, the list flow of goods in a store in Taobao APP and the information flow on the home page are all list page data with super-long content. For long list page, long the UI pages can lead to excessive memory footprint, and in the user’s device, memory is the most important indicators, for the current domestic market of APP, low-end cell phone still take a lot of market, for the equipment, once the memory, the APP is easy to OOM, which leads to the user experience is very bad, In the current highly competitive market environment, poor experience means losing users.

For traditional imperative programming, we can actively control the reuse of UITableViewCell and build our own buffer pool to optimize our APP memory footprint. However, for SwiftUI 1.0, there is no effective way to control the rendering of pages provided by the system. Large list pages are prone to memory overload.

SwiftUI 2.0, with LazyHStack and lazyVStack plus List rendering mode which defaults to Lazy, directly solves the biggest performance problem.

The author took the Emas App written with SwiftUI last year as an example. When the list page (without large picture) was loaded to 500, the memory usage of the App had reached nearly 360MB. Just switch to the Xcode12 API and adjust to LazyVStack to reduce the memory footprint by 300MB.

Widget and Clips

WidgetKit from Apple and WWDC 20 supports SwiftUI Only. Although you can already mix some views in UIkit, But no one is going to opt for a clunky imperative API for a Widget with the lowest supported version of iOS14 without historical baggage.

The same goes for Clips. Due to the lack of space, there will be a special article to analyze related technologies.

What are the opportunities for Swift & SwiftUI?

The author once promoted the group to upgrade infrastructure in the company, supported Swift development environment and launched some scenes on Taobao. However, there have been some doubts in the group. What is the use of introducing Swift?

SwiftUI is another gadget for years to come. Isn’t Objective-C enough? Now I can answer these questions about Swift’s future opportunities in efficiency, experience and Apple’s technology dividend.

The efficiency of

In terms of research and development efficiency, Swift is self-evident in its simplicity compared with Objective-C. The number of module codes on-line in Taobao APP by the author has decreased by 40%.

But going one step further, if you switch from UIKit to SwiftUI the amount of code is more than twice as much. Less code means faster delivery and more trial and error scenarios in today’s competitive market.

As for the comparison of code volume between WRITING code using UIKit and SwiftUI, readers can refer to the open source APP MovieSwiftUI for an intuitive understanding.

experience

The reader may be confused by the fact that switching languages and frames doesn’t seem to help the experience, but is it?

After the introduction of Swift, since Swift language was designed with security as the most important goal, the introduction of Swift will make the code reduce undefined behaviors as much as possible. Reducing Crash means the stability of APP is improved and the experience is naturally better.

Secondly, Swift has more instructions compiled than Objective-C for security purposes, but what if all the UI is written in SwiftUI?

Less code means smaller package size. Currently, the size of the APP package on the iOS end of domestic giants is heading towards 200MB. If we can reduce the size of the package with more code, we can also carry more business under the limit of 200MB. The user experience has also been greatly improved.

Further, as Swift chooses to use value types to build the entire APP, the advantage of value types lies in a flatter inline data structure to allocate memory instead of using more indirect pointer references, which reduces a lot of unnecessary heap memory consumption, meaning a reduction in overall memory usage. It also greatly improves the stability of the whole APP.

Apple’s Choice

Swift as apple’s strategic language has grown stronger and stronger, and Apple has invested more and more in Swift since the Swift ABI became stable in 2019. We can go in /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/lib/swift , /Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/System/Library/F Rameworks, github.com/apple and github.com/swift-serve… Since iOS 13, Apple has added about 10+ Pure Swift Libraries, 10+ Open Source Swift Libraries, and 144 Open frameworks, 57 Framework apis have been redesigned according to Swift Style.

From the following data:

1. Apple has stopped using Objective-C for Sample Code demonstrations since WWDC17

Developer.apple.com/ No longer updates objective-C documentation

WidgetKit is SwiftUI Only.

4. SwiftUI is the most suitable frame for the package size of 10M App Clips

5. The open source community is moving away from Objecive C like Lottie.

It can be judged that Swift is the only choice for Apple platform in the future. The more burdened the big factory APP is, the more difficult it will be in the future if it does not reserve as soon as possible.

What do we need to do?

Swift

What have we done

1. A research and development environment that supports Swift binary

2. 300+ supports mixed tao SDK.

3. Six modules of hand shopping were landed.

4. The Group has added about 20 apps supporting Swift.

5. More than 10 technical trainings.

169+ language finch knowledge precipitation.

7, 300+ engineers group Swift official organization.

8. Two technologically innovative products

Through the concerted efforts of the horizontal organization last year, we have already supported the horizontal large-scale infrastructure. Including research and development environment, tool support, deposited a large amount of documentation, as well as related technical courses.

In what direction should we work

At present, the group is increasingly calling for Swift, and a large number of our engineers hope to use Swift. At present, the first thing we need to do is to improve our development experience by relying on Swift and SPM, upgrade our middleware, enable businesses to use Swift in large quantities, and improve our r&d efficiency and code quality.

Upgrade the new package management system based on SPM

2. Upgrade the old base and polish the new generation of infrastructure.

3. Introduce new Swift specific library enabling business.

SwiftUI

Although many advantages of SwiftUI have been mentioned above, including r&d efficiency and improved experience, SwiftUI also has its fatal disadvantages in the domestic environment

1. IOS 14 is safe to use.

2. Only support Apple Platform, which conflicts with the concept of supporting Mobile Platform in China.

Big apps need to figure out how to deploy to the lower versions of the operating system and Android platform. After all, many companies still support iOS 9. Upgrading to iOS 14 is still a century away, and Android is still the majority of domestic devices.

While we’ve seen Swift support for Android, we’ve also seen Apple’s lack of interest in SwiftUI for Android.

Flutter is not as good as SwiftUI in terms of experience, but SwiftUI is still inferior to Flutter for the domestic market with strong cross-end desire. However, since SwiftUI’s DSL layer has been basically fixed, It is also possible to implement a homegrown SwiftUI engine directly on earlier versions of the operating system, or port the SwiftUI engine to Android, for example by docking with Flutter or directly with Android Native.

SwiftUI’s choice to retain the iOS experience and only hack into one end of the Flutter is obviously better than the incremental package size and inconsistent experience that Flutter introduces with two ends.

However, in the short term, we can start to use SwiftUI in Clips and Widget scenarios. After all, SwiftUI’s rapid development efficiency and low package size are very suitable for such scenarios. We can practice and reserve our SwiftUI in business scenarios. Try it out in the main APP.

Mobile Client Architecture group

Responsible for taobao client infrastructure including modular container, starter, routing, and UI framework, responsible for the high availability including Crash, caton, memory, power consumption, such as monitoring, responsible for the overall performance and experience optimization, responsible for key technology including storage, log, repair, etc., is responsible for the system to explore new features, new technology, new equipment, Here you will face huge technical challenges brought by massive users, large-scale business and double Eleven Promotion. You can work side by side with senior bull, study and solve complex problems in the system kernel, and quickly grow into an excellent engineer in the industry!

Resume: [email protected]

reference

Behind SwiftUI

MovieSwiftUI

SE-0281-main-attribute.md

Add custom views and modifiers to the Xcode Library

Structure your app for SwiftUI previews

Introduction to SwiftUI

What’s new in SwiftUI

App essentials in SwiftUI

Visually edit SwiftUI views

Stacks, Grids, and Outlines in SwiftUI

Build document-based apps in SwiftUI

Data Essentials in SwiftUI

Build a SwiftUI view in Swift Playground

Build SwiftUI apps for tvOS

Build SwiftUI views for widgets

Build complications in SwiftUI

What’s new in Swift

Swift packages: Resources and localization

Distribute binary frameworks as Swift packages

Explore logging in Swift

Create Swift Playgrounds content for iPad and Mac

Embrace Swift type inference

Explore numerical computing in Swift

Unsafe Swift

Safely manage pointers in Swift

Explore numerical computing in Swift

Explore Packages and Projects with Xcode Playgrounds

Use Swift on AWS Lambda with Xcode