Mobile Development 16 min read

Mastering Swift in Baidu App: Common Pitfalls and Practical Solutions

This guide explores Swift's advantages for iOS development, outlines suitable migration scenarios, and provides detailed solutions for common issues such as string handling, error management, access control, JSON parsing, initialization rules, Objective‑C interop, modulemap configuration, and Library Evolution constraints.

Baidu Geek Talk
Baidu Geek Talk
Baidu Geek Talk
Mastering Swift in Baidu App: Common Pitfalls and Practical Solutions

Swift is a modern programming language for iOS/macOS development. Since Swift 5 introduced ABI stability, it offers advantages over Objective‑C in safety, performance and developer productivity.

When to Adopt Swift

Most Objective‑C codebases can be migrated, but avoid Swift in scenarios that rely heavily on runtime dynamism, core logic that must remain stable, direct C++ calls, or classes that cannot be subclassed by Swift.

Pre‑migration Checklist

Ensure the project and individual modules support Swift.

Plan mixed‑language modules for large codebases.

Set SWIFT_TREAT_WARNINGS_AS_ERRORS=YES to enforce clean Swift code.

Maintain public headers in the umbrella header after modularisation.

Basic Swift Usage

2.1 Why Strings Feel Awkward

Swift strings are composed of grapheme clusters, whose length varies, so integer indexing is not allowed. Adding a subscript extension that converts an Int to a String.Index solves the problem.

extension String {
    subscript(i: Int) -> Character {
        return self[self.index(startIndex, offsetBy: i)]
    }
}

2.2 Difference Between try , try? and try!

try

: Propagates errors to a catch block. try?: Returns an optional; nil on error. try!: Forces unwrapping; crashes if an error occurs.

In Baidu App, try? is the recommended pattern for file operations.

2.3 public vs open

public

classes cannot be subclassed outside their module, while open classes can. Consequently, open provides a higher level of exposure.

2.4 JSON Parsing

Manual dictionary conversion is verbose. Third‑party libraries such as SwiftyJSON, ObjectMapper, or the built‑in JSONEncoder / JSONDecoder simplify the process.

2.5 Required init?(coder:) for UIView Subclasses

Required by the NSCoding protocol.

Needed when a subclass defines a designated initializer.

Invoked automatically when a storyboard loads the view.

Remove fatalError calls to avoid crashes.

2.6 Two‑Phase Initialization Rules

All stored properties must be assigned before calling a superclass initializer.

Designated initializers must delegate upward before setting inherited properties.

Convenience initializers must call another initializer of the same class first.

During phase 1, you cannot read instance properties, call instance methods, or use self as a value.

Objective‑C ↔ Swift Interoperability

3.1 Calling Public OC Headers from Swift

// In the module’s umbrella header
#import "XYZ.h"
// Swift can now import the module
import XYZ

3.2 Accessing Private OC Headers

Create a private modulemap, add it to MODULEMAP_PRIVATE_FILE, and import the private module in Swift.

framework module NewModule_Private {
    header "xxxxx.h"
}

3.3 Exposing Swift Classes to OC

Subclass NSObject and mark the class with @objc.

Make the class public or open.

Import the generated Swift header in OC files.

3.4 Forward Declarations and Nullability

When an OC API is declared nonnull but returns nil, Swift treats it as a non‑optional and crashes at runtime. Use proper nullability annotations and runtime checks.

3.5 Library Evolution Constraints

Enabling BUILD_LIBRARY_FOR_DISTRIBUTION (Library Evolution) requires iOS 13+ for @objc members in extensions. Mixing Swift and OC under this setting may cause compile‑time or runtime incompatibilities.

Other Common Issues

4.1 Sparse Xcode Error Messages

Often caused by Swift components depending on non‑modularised OC modules. Ensure all dependencies are modularised or add an empty Swift file to force module creation.

4.2 Library Evolution Compilation Errors

Errors such as “@objc instance method … requires iOS 13” indicate that the consuming target must target iOS 13 or later.

4.3 Private Header Import Style

Using angled brackets ( <header.h>) hides the header from other targets; configure HEADER_SEARCH_PATHS to allow both quote and bracket imports.

By documenting these pitfalls and their remedies, Baidu’s front‑end team aims to smooth the transition to Swift, improve code quality, and maintain compatibility with existing Objective‑C infrastructure.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

iOSSwiftError HandlingInitializationLibrary EvolutionModulemapObjective-C Interop
Baidu Geek Talk
Written by

Baidu Geek Talk

Follow us to discover more Baidu tech insights.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.