• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Migrating from Swift to ArkTS
2
3<!--Kit: ArkTS-->
4<!--Subsystem: ArkCompiler-->
5<!--Owner: @fanglou-->
6<!--Designer: @qyhuo32-->
7<!--Tester: @kirl75; @zsw_zhushiwei-->
8<!--Adviser: @zhang_yixin13-->
9
10ArkTS is a new programming language that brings new development experience and opportunities to developers familiar with Swift. It inherits the features of modern languages in terms of syntax and programming paradigms, and is deeply optimized for the ecosystem. Understanding the differences and commonalities between Swift and ArkTS can help you quickly get started with application development and avoid common programming pitfalls.
11
12This topic compares ArkTS with Swift from the perspective of basic syntax, language structure, and type system. For details, see [Introduction to ArkTS](./introduction-to-arkts.md).
13
14## Exploring the Differences Between Swift and ArkTS
15
16The following will sort out the misunderstandings and pitfalls you may encounter when migrating a Swift project to ArkTS due to differential syntax, type system, and application development mode. You are advised to master the basic syntax and runtime behavior of ArkTS, and then focus on the differences between ArkTS and Swift.
17
18## Basic Syntax
19
20### Variable Declaration
21
22**Sample code in ArkTS**:
23
24```typescript
25// Type annotation (similar to Swift).
26let age: number = 20;
27const program: string = 'ArkTS';
28
29// Type inference (similar to that of local variable in Swift).
30let version = 5.0;
31```
32
33### Primitive Types
34| Swift      | ArkTS           | Sample Code                         | Key Difference                 |
35|----------------|----------------------|-----------------------------------|-------------------------------|
36| `Bool`    | `boolean`     | `let isDone: boolean = false;`    | They are defined similarly and used for logical judgments in Swift and ArkTS.                     |
37| `Int8`    | `number`      | `let count: number = 10;`         | Swift: the value of **Int8** type is an 8-bit integer.<br>ArkTS: **number** represents small-range integer type. |
38| `Int16`   | `number`      | `let count: number = 10;`         | Swift: the value of **Int16** type is a 16-bit integer.<br>ArkTS: **number** represents small-range integer type.|
39| `Int32`   | `number`      | `let count: number = 10;`         | Swift: the value of **Int32** type is a 32-bit integer.<br>ArkTS: **number** represents double-precision floating-point type, which can store integers and floating-point numbers.      |
40| `Int64`        | `number`             | `let largeNum: number = 9007199254740991;` | Swift: **Int64** represents large-range integer type.<br>ArkTS: **number** represents all numeric types.         |
41| `Float`        | `number`             | `let pi: number = 3.14;`          | Swift: **Float** needs to be explicitly specified.<br>ArkTS: `number` can be used directly.      |
42| `Double`       | `number`             | `let e: number = 2.71828;`        | Swift: the **Double** type is used.<br>ArkTS: **number** represents all numeric types.        |
43| `Character`    | `string`             | `let c: string = 'a';`            | ArkTS: **string**, instead of **Character**, is used to represent string type.  |
44| `String`       | `string`             | `let message: string = 'Hello';`  | They are defined similarly, but the **string** type of ArkTS supports template literals and more flexible operations. |
45
46### Complication Types
47| Swift               | ArkTS           | Sample Code in ArkTS                                                                | Key Difference                                                                |
48|-----------------------------|--------------------------|-------------------------------------------------------------------------|-----------------------------------------------------------------------------|
49| **Array**: `var arr: [Int] = [1, 2, 3]`| **Array**: `let arr: Array<number> = [1, 2, 3];`| `// Initialize an array at dynamic length. Syntactic sugar is used.`<br>`let dynamicArr = [4, 5, 6];`<br>| The length of a Swift array can be changed.<br>The length of an ArkTS array is dynamic. Operations such as **push** and **pop** are supported. You can use **[]** to simplify initialization. ArkTS array does not go out of bounds. If the array subscript exceeds the array length, **undefined** is returned.|
50| **Set**: `var mySet: Set<String> = ["a", "b"]`| **Set**: `let mySet: Set<string> = new Set(["a", "b"]);`| `mySet.add('c'); // Add an element to the set.`<br>`for (const item of mySet) {...); // Iterate through the set.`<br>| Swift sets are declared by specifying types.<br>ArkTS sets are flexible and suitable for dynamic scenarios.|
51| **Dictionary**: `var dict: [String: Int] = ["key": 1]`| **Map**: `let map: Map<string, number> = new Map();`| `map.set('key', 1); // Add a KV pair.`<br>`let value = map.get('key'); // Obtain the value.`<br>`map.has('key'); // Check whether the key exists.`<br>| Swift **Dictionary** requires explicit declaration of types.<br>ArkTS Map supports chain calls, which is more direct.|
52| **Protocol**: `protocol Shape { func area() -> Double }`| **interface**: `interface Shapes { area(): number; }`| `class Rectangles implements Shapes {`<br>`  public width: number = 0;`<br>`  public height: number = 0;`<br>`  area(): number { return this.width * this.height; }`<br>`}`<br>| The syntax structures of Swift and ArkTS are similar, but ArkTS APIs do not require explicit modifiers and support optional properties.|
53| **Class**: `class Circle: Shape { /* Class definition */ }`| **class**: `class Circles implements Shape { /* Class definition */ }`| `class Circles {`<br>`  radius: number;`<br>`  constructor(radius: number = 10) { // Support default parameter values.`<br>`    this.radius = radius;`<br>`  }`<br>`}`<br>| ArkTS classes support default property values and optional parameters. Constructor parameters can be directly declared as class properties, which is more concise.|
54| **Enumeration**: `enum Color { case red, green, blue }`| **enum**: `enum Colors { Red, Green, Blue }`| `enum Colors { Red = 1, Green, Blue };`<br>`let color = Colors.Green; // The value is 2, which is automatically incremented.`<br>| The basic concepts are the same. However, ArkTS enum does not support custom constructors and methods like Swift. Only a simple numeric or string enum is supported.|
55
56### Functions and Closures
57
58The syntax of functions in Swift and ArkTS is similar, but there are subtle differences.
59
60Similarities: regular function definition and arrow function.
61
62**Sample code in ArkTS**: function definition
63
64```typescript
65// Regular function definition, similar to that in Swift.
66function add(x: number, y: number): number {
67    return x + y;
68}
69
70// Concise arrow function definition, similar to the closure syntax in Swift.
71const multiply = (a: number, b: number): number => a * b;
72```
73
74Differences:
75
761. ArkTS provides polymorphism at the type declaration level, which is used only for type check and document prompt. There is only one implementation function.
77
78**Sample code in ArkTS**: ArkTS function overloading
79
80```typescript
81function foo(x: number): void;            /*  First function definition  */
82function foo(x: string): void;            /*  Second function definition  */
83function foo(x: number | string): void {  /*  Function implementation       */
84}
85
86foo(123);     // Use the first function definition.
87foo('aa'); // Use the second function definition.
88```
89
902. ArkTS uses **?** for optional parameters, for example, **function foo(name?: string)**, instead of the default value syntax in Swift.
91```typescript
92function foo(name?: string){}  /*  name is an optional parameter.  */
93
94foo('hello');     //  Pass in the name parameter.
95foo();     //  Do not pass in the name parameter.
96```
97
98### Utils
99
100The ArkTS basic class library and container class library enhance the basic features of the programming language, including high-precision floating-point operations, binary buffer, XML generation, parsing, conversion, and multiple container libraries, reducing development workload and improving efficiency.
101
102## Language Structure
103
104Swift is a modern language that integrates object-oriented, functional, and protocol-oriented paradigms. It emphasizes security, performance, and simplicity, and is suitable for cross-platform development.
105
106ArkTS integrates declarative UI, functional, and object-oriented paradigms. Leveraging its reactive system and cross-device adaptation capabilities, ArkTS efficiently builds high-performance applications with consistent experiences across multiple devices.
107
108### Module and Package Management
109
110Swift allows you to use modules to organize code and import classes in other modules using the **import** statement.
111
112ArkTS also has its own module and package management mechanism, and uses the **import** statement to import functions in other modules.
113
114**Sample code in ArkTS**:
115
116```
117// Import the ArkTS container set in the ArkTS standard library.
118
119import { collections } from '@kit.ArkTS';
120```
121
122The module system of ArkTS focuses more on modular development and code reuse, so it can conveniently manage dependencies between different functional modules. In this case, the usage is different from that of Swift module management.
123
124### Class and Namespace
125
126The class system of ArkTS is similar to that of Swift in syntax, but it offers more advanced features.
127
128| Feature      |Swift Implementation     | ArkTS Implementation           | Description                         |
129|------------|------------|------------------|-------------------------------|
130| Namespace organization   | Nested structure/inner class    | **namespace** keyword or module file structure          | Supports the mixed mode of explicit namespace and modular organization.  |
131| Inheritance mechanism       | Class-based inheritance mechanism       | Prototype chain-based inheritance mechanism          | Similar syntax with differential underlying mechanism.       |
132| Class member visibility   | public/private/internal       | Same as Java, but supports module-level visibility control.         | Added the dimension for controlling module export.|
133
134**Namespace management**
135
136ArkTS supports explicit namespaces and modular organization.
137
138**Sample code in ArkTS**:
139
140```typescript
141namespace Models {
142    export class User {
143        // Implementation details.
144    }
145
146    export interface Repository {
147        // API definition.
148    }
149}
150```
151
152Compared with the combination of module and inner class in Swift, the namespace in ArkTS can be used to implement a more intuitive code layering.
153
154### Asynchronous Programming Model
155
156**Single-threaded or multi-threaded processing**
157
158Swift uses **async** or **await** and task to implement asynchronous programming and uses multi-threading and **DispatchQueue** to implement concurrency.
159
160Based on the event loop, ArkTS uses a promise, **async**, or **await** to process asynchronous tasks, preventing the main thread from being blocked.
161
162**Error handling**
163
164In Swift, use **try/catch** to capture exceptions in synchronous code. For asynchronous code, handle exceptions in a special manner.
165
166Uncaptured promise errors in ArkTS may cause silent failures. You need to explicitly use **try/catch** or **.catch**.
167
168### Binding of self
169
170In Swift, **self** always points to the instance of the current class, which is determined by the code structure during compilation. In a method, **self** points to the object instance that calls the method. The instance pointed by **self** cannot be changed by calling the method.
171
172**Sample code in Swift**:
173
174```swift
175class MyClass {
176  func method() {
177    print(self) // Always points to the instance of MyClass.
178  }
179}
180```
181
182In ArkTS, the instance pointed by **this** is determined by the context when the function is called.
183
184**Sample code in ArkTS**:
185
186```typescript
187class A {
188  bar: string = 'I am A';
189
190  foo() {
191    console.info(this.bar);
192  }
193}
194
195class B {
196  bar: string = 'I am B';
197
198  callFunction(fn: () => void) {
199    fn();
200  }
201}
202
203function callFunction(fn: () => void) {
204  fn();
205}
206
207let a: A = new A();
208let b: B = new B();
209
210callFunction(a.foo); // Program crashes. The context of this changes.
211b.callFunction(a.foo); // Program crashes. The context of this changes.
212b.callFunction(a.foo.bind(b)) // Output 'I am B'.
213```
214
215## Type System
216
217The type system of ArkTS is different from that of Swift.
218
219### Type Inference and Optional Types
220
221Compared with Swift that requires explicit type declaration and strict null check, the type system of ArkTS provides more flexible expression modes.
222
223ArkTS has powerful type inference capabilities. The compiler can automatically infer the type of a variable based on the context. Therefore, you do not need to explicitly declare the type of a variable in most cases.
224
225**Sample code in ArkTS**:
226
227```typescript
228let num = 10; // The compiler automatically infers that num is of the number type.
229```
230
231In addition, ArkTS supports optional types. You can add a question mark (?) to the end of a type to indicate that the variable can be **null** or **undefined**.
232
233**Sample code in ArkTS**:
234
235```typescript
236interface Person {
237  name: string;
238  age?: number;  // age is an optional property.
239}
240
241const person: Person = {
242  name: "Alice",
243};
244```
245
246### Union Type
247
248Union type provides type combination capability for complex scenarios, which is an important innovation of the ArkTS type system.
249
250ArkTS supports union types (separated using **|**). A union type indicates that a value can be one of multiple types.
251
252**Sample code in ArkTS**:
253
254```typescript
255// Example of a union type.
256
257let value: string | number;
258value = 'hello';
259value = 123;
260
261```
262