Доклад: SwiftUI Inside / Александр Скворцов (Яндекс)

Доклад: SwiftUI Inside / Александр Скворцов (Яндекс)

Introduction to Swift UI Insights

Welcome and Session Overview

  • The session is introduced by Евгений Ануфрейчик, who welcomes attendees to the evening session of Подлодка Crew focused on Swift.
  • Никита Краснов joins as a co-host, and they introduce Саша Скворцов from Яндекс, who will present insights about Swift UI.

Presentation Context

  • Саша begins by highlighting that the presentation will cover lesser-known aspects of Swift UI not well-documented online.
  • A humorous anecdote is shared regarding an April Fool's joke about Swift being written in 2010 on Flash, setting a light-hearted tone for the talk.

Challenges with Swift UI Development

Initial Experiences with Swift UI

  • The discussion starts with experiences developing applications using iOS 15 and how expectations were set high based on Apple's promises about Swift UI.
  • Developers encountered bugs during development; some were due to misunderstandings while others stemmed from issues within the framework itself.

Memes and Developer Culture

  • A local meme emerged among developers when encountering bugs attributed to "Swift UI," illustrating frustrations faced during development.

Animation Challenges in Swift UI

Animation Implementation

  • An example code snippet demonstrates animating a red circle inside a blue circle based on a flag condition.
  • The difference between traditional UIKit animations and those in Swift UI is discussed, emphasizing how animations behave differently due to architectural choices.

Core Animation vs. Swift Animation

  • It’s noted that Core Animation operates in a separate process, allowing it to function independently of application state pauses, unlike animations in Swift which can be interrupted more easily.

Navigation Issues in Swift UI

Navigation View Limitations

  • The presentation shifts focus to navigation challenges within standard Navigation Views, including unresponsive buttons despite visual feedback indicating interaction.

State Management Problems

  • Developers face difficulties managing state transitions effectively within Navigation Views due to inherent limitations in API design at the time (iOS 16).

Conclusion of Current Discussion Points

  • As the discussion wraps up this section, Sаша emphasizes ongoing challenges with state management when navigating views that involve complex states or nested objects.

Understanding State Management in SwiftUI

Managing View States with Hosting Controllers

  • The discussion begins with the concept of resetting view states to zero when a view is wrapped in a hosting controller, emphasizing that methods like onAppear and onDisappear are called appropriately.
  • It is noted that hiding views using opacity retains state but does not trigger critical business logic methods (onAppear, onDisappear), which can lead to issues in functionality.
  • A real-world example illustrates the challenge of loading images on screen entry, highlighting the difficulty of implementing custom navigation without proper state management tools.
  • The speaker references a conversation with an engineer at Dobdop DC 2023, confirming that there is no way to maintain view state without using a hosting controller.
  • Questions arise about how Navigation View maintains state during transitions; it’s clarified that Navigation Link wraps its content in a hosting controller.

Clarifying Navigation Link Behavior

  • An inquiry into previous questions regarding Core Animation leads to further exploration of how UI components interact within navigation contexts.
  • The speaker discusses the absence of direct UIView components in Navigation Link code, indicating that it pushes a view controller from AnyView instead.
  • There’s confusion about whether Navigation Link should work within navigation stacks; it's confirmed through chat discussions that it does not function as expected in this context.
  • The limitations of using modifiers like Navigation Destination are highlighted, suggesting they are necessary for proper functionality within navigation stacks.
  • A consensus emerges regarding invalid behavior when running code under different conditions, reinforcing the need for clarity around component interactions.

Insights on Animation Mechanics

  • Questions about animation mechanics prompt discussions on what underlies SwiftUI animations beyond Core Animation; Metal is mentioned as part of the underlying technology stack.
  • Fundamental bugs persist across OS versions due to complexities in building navigation systems from scratch; these issues remain unresolved over time.
  • GPU acceleration is suggested as essential for smooth animations and effects like blurs and Gaussian blur implementations within SwiftUI applications.

Exploring Scroll Views Limitations

  • Transitioning to scroll views, the speaker critiques standard Scroll View implementations as lacking features and slow updates for enhancements needed by developers.
  • A workaround involving stable ABI (Application Binary Interface) modules allows access to human-readable module descriptions alongside binary ones for better development insights.
  • The discovery process involves searching through available frameworks (e.g., ST Core), revealing hidden functionalities such as _Scroll, which could enhance development practices.

Understanding Swift UI and Its Underlying Mechanics

Issues with Lazy Containers in Scroll Views

  • The content of the scroll view is largely ineffective due to the lack of lazy loading, which is crucial for handling long content efficiently.
  • A discussion on the importance of addressing practical issues in technology usage rather than just theoretical knowledge.

Challenges in Understanding Technology

  • Documentation can be insufficient; real-world problems often arise that are not covered in guides, leading to unexpected behavior in code.
  • There’s a disparity between well-documented technologies and those lacking comprehensive resources, complicating developers' understanding.

Exploring AG Framework

  • Swift UI's structure reveals it operates more like C++ UI, as indicated by symbols found during debugging.
  • The AG framework is a private framework accessible within macOS SDK and runtime environments, raising concerns about reverse engineering.

Analyzing Object File Symbols

  • A command is introduced to print object file symbols, revealing 730 available symbols for exploration related to the AG framework.

Connection Between AG and Swift UI

  • The Swift Interface shows an empty structure that hints at internal fields referencing entities from the attribute graph.
  • The View protocol contains additional methods beyond just Body, indicating deeper functionality tied to internal workings.

Implementing Hidden Methods

  • Realizing hidden methods leads to their invocation instead of standard views when implemented correctly.

Understanding State Management

  • The state property implements Dynamic Property protocol; examining this reveals how properties are managed internally within Swift UI.

Event Handling in View Graph

  • When a view is added to the graph, initial values are set up based on its structure. This process involves memory layout management for dynamic properties.

Understanding State in SwiftUI

The Role of State in Views

  • The state can only be used from within the view, meaning changes made in the constructor do not affect it.
  • Observations show that initial values set for state variables are stored correctly in memory, confirming their integrity during runtime.
  • A conversion was made for better readability; however, pointers must be read directly to understand their actual location and value.

Observing Changes and Optimizations

  • The presence of a flag (e.g., "red") suggests its potential use in observation optimizations where only affected bodies update upon state changes.
  • Practical application of knowledge indicates sibling states are unaffected by external changes due to their initialization with null values.

Discussion on Private APIs

  • Questions arise regarding the usage of private APIs in SwiftUI; many developers utilize hidden APIs without realizing it since they are not strictly enforced by Apple.
  • These so-called private APIs serve as inline tools for compiler efficiency but can be freely used as they are embedded within applications.

Attribute Graph Functionality

  • The attribute graph functions similarly to a hierarchy in UIKit, managing how SwiftUI understands what needs rendering or animating based on state changes.

Where Does State Reside?

  • State lives within the attribute graph; when creating an instance without proper linkage, it remains inactive despite having defined properties.
  • Modifications to state outside its designated context (like siblings or parents changing it directly) will not impact its functionality unless properly connected.

Understanding Non-Mutating Sets and State Management

The Role of Non-Mutating Sets

  • A non-mutating set allows values to be recorded despite the underlying structure, but it requires knowledge of where to write these values.
  • The state becomes aware of where to write when make property is invoked, enabling the view to indirectly write into the attribute graph.

Serialization in Frameworks

  • Serialization is crucial for tools like debuggers, as code execution can occur across different processes or devices.
  • Various formats exist for serialization; JSON (Jon) is one example that indicates a broader serialization mechanism.

Widget Interactivity Limitations

  • Widgets cannot utilize closures due to their design constraints; interactivity must be achieved through URLs and intents.
  • Serialized layouts appear as arrays of nodes forming a tree structure, with each node containing properties identified by IDs and attributes.

Insights on Attribute Graph Structure

  • Even simple views can generate extensive serialized JSON data, indicating that the graph stores not only input data but also computed results like node sizes.
  • This leads to discussions about snapshot states and widget lifecycle management within serialization contexts.

Applying Knowledge from the Presentation

Practical Applications of Technology Understanding

  • Understanding internal workings helps developers create better practices and guidelines for using technology effectively.
  • Clear explanations regarding state usage emphasize that state should only be manipulated from specific contexts (e.g., body).

Challenges in Application Development

  • Apple's documentation may seem concise but often lacks depth when implementing complex features, leading to various challenges during development.
  • Swift QI is positioned as a high-level API rather than a replacement for UIKit, suggesting ongoing relevance for UIKit in future developments.

Final Thoughts and Community Engagement

Encouragement for Exploration

  • Developers are encouraged to explore available tools without needing additional purchases or downloads; existing resources are sufficient for learning.

Addressing Common Issues

  • Discussion includes addressing animation issues with circles in UI elements; alternative solutions involve hiding problematic elements instead of fixing them directly.

Discussion on Swift Development and UI Integration

Insights on Scroll View and List Usage

  • The speaker mentions a complex case where a simple insertion in UIKit could suffice, hinting at the ease of using UIKit for certain tasks.
  • There is uncertainty about how to use lists effectively, with speculation that lists may utilize table views internally.
  • Emphasizes the importance of sharing useful findings within the community to improve applications collectively.

Custom Navigation Controllers

  • Discussion revolves around creating a custom wrapper for navigation controllers, highlighting unique behaviors such as back actions that depend on the hierarchy of navigation controllers.
  • The speaker notes issues with their custom wrapper not causing bugs that were previously encountered, indicating improvements in stability.

Handling Binary Dumps in Swift and C++

  • A question arises regarding how to properly dump Swift and C++ from binaries; it’s noted that C++ symbols contain full signatures while C symbols only have names.
  • The speaker reflects on their lack of experience with this process but acknowledges positive feedback from others regarding the response given.

UI Kit's Role in SwiftUI

  • Clarification is sought about how UIKit operates within SwiftUI; the speaker shares experiences using UIKit components when facing challenges with animations in SwiftUI.
  • They mention successfully implementing infinite animations by leveraging UIKit, suggesting confidence in mixing frameworks when necessary.

Best Practices for Using APIs

  • A warning is issued against improperly returning instances from API calls, which can lead to bugs due to unintended multiple instances being created.
  • The importance of correctly utilizing APIs is stressed, particularly regarding instance creation in SwiftUI structures to avoid display issues.
Video description

Заглянем за кулисы публичных интерфейсов. Раскопаем недокументированные особенности и подробности внутреннего устройства. Контакты спикера: https://t.me/alexander_skvortsov Материалы из доклада: https://drive.google.com/file/d/1zWmT1h0XPLhl21G8NkpPTzXi93HGj5HP/view?usp=share_link https://rensbr.eu/blog/swiftui-attribute-graph/ https://github.com/OpenSwiftUIProject/AGDebugKit Понравилось видео и хочешь узнать что-то еще про Podlodka iOS Crew? Забирай весь плейлист на https://podlodka.io/crew-records или покупай годовой доступ ко всей Библиотеке контента.