鸿蒙学习实战之路-Swift 开发者快速上手 ArkTS 指南

最近在 Apple 开发者群里潜水,发现好多 Swift 大佬都在问:“听说鸿蒙的 ArkTS 很火,但我只会写 iOS,这语言会不会跟 Objective-C 一样难啃啊?”(┓( ´∀` )┏)

作为一个从 SwiftUI 转鸿蒙开发的"叛逃者"_,今天我就用 Swift 开发者熟悉的方式,带你 10 分钟快速上手 ArkTS!不用怕语法差异,咱们用对比的方式学,保证看完就能写个能跑的小应用!


在这里插入图片描述

1. 先搞懂:ArkTS 和 Swift 的"亲戚关系"

其实 ArkTS 和 Swift 在设计理念上很像,都是:

  • 静态类型语言,注重类型安全
  • 支持面向对象和函数式编程
  • 语法简洁,可读性强

最大的区别是:ArkTS 基于 TypeScript,更像"带类型的 JavaScript",而 Swift 是 Apple 生态的原生语言。

2. 核心语法对比:从 Swift 到 ArkTS

咱们直接上代码对比,用最常用的语法点帮你快速转换思维!

2.1 变量与常量

Swift 写法:

// 常量
let name = "盐焗西兰花"
let age: Int = 18

// 变量
var count = 0
var isActive: Bool = true

ArkTS 写法:

// 常量
const name: string = "盐焗西兰花";
const age: number = 18;

// 变量
let count: number = 0;
let isActive: boolean = true;

🥦 西兰花小贴士:

  • ArkTS 用const代替 Swift 的let定义常量
  • 数据类型名称略有不同:IntnumberBoolbooleanStringstring
  • 每行代码结尾需要加分号

2.2 函数定义

Swift 写法:

func greet(person: String) -> String {
    return "Hello, \(person)!"
}

// 调用
let message = greet(person: "Swift开发者")

ArkTS 写法:

function greet(person: string): string {
    return `Hello, ${person}!`;
}

// 调用
let message: string = greet("ArkTS开发者");

🥦 西兰花小贴士:

  • ArkTS 用反引号和${}做字符串插值,代替 Swift 的\()
  • 函数参数不需要外部参数名
  • 箭头方向都是->,这点很友好!

2.3 条件语句

Swift 写法:

let score = 85

if score >= 90 {
    print("优秀")
} else if score >= 80 {
    print("良好")
} else {
    print("继续努力")
}

ArkTS 写法:

let score: number = 85;

if (score >= 90) {
    console.log("优秀");
} else if (score >= 80) {
    console.log("良好");
} else {
    console.log("继续努力");
}

🥦 西兰花小贴士:

  • ArkTS 的条件判断需要用小括号包裹
  • 打印函数用console.log()代替print()

2.4 循环语句

Swift 写法(for-in):

let fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits {
    print("我喜欢吃\(fruit)")
}

ArkTS 写法(for-of):

let fruits: string[] = ["苹果", "香蕉", "橙子"];
for (let fruit of fruits) {
    console.log(`我喜欢吃${fruit}`);
}

Swift 写法(while):

var i = 0
while i < 3 {
    print(i)
    i += 1
}

ArkTS 写法(while):

let i: number = 0;
while (i < 3) {
    console.log(i);
    i++;
}

🥦 西兰花小贴士:

  • ArkTS 用for-of代替 Swift 的for-in遍历数组
  • 自增运算符i++和 Swift 一样,但 ArkTS 还支持++i

2.5 类与结构体

Swift 写法:

// 结构体
struct Person {
    var name: String
    var age: Int

    func introduce() {
        print("我叫\(name),今年\(age)岁")
    }
}

// 类
class Student: Person {
    var studentId: String

    init(name: String, age: Int, studentId: String) {
        self.studentId = studentId
        super.init(name: name, age: age)
    }

    override func introduce() {
        print("我叫\(name),今年\(age)岁,学号是\(studentId)")
    }
}

// 使用
let student = Student(name: "小明", age: 18, studentId: "2024001")
student.introduce()

ArkTS 写法:

// 类(ArkTS中结构体用interface或class实现)
class Person {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    introduce(): void {
        console.log(`我叫${this.name},今年${this.age}岁`);
    }
}

// 继承
class Student extends Person {
    studentId: string;

    constructor(name: string, age: number, studentId: string) {
        super(name, age);
        this.studentId = studentId;
    }

    override introduce(): void {
        console.log(`我叫${this.name},今年${this.age}岁,学号是${this.studentId}`);
    }
}

// 使用
let student: Student = new Student("小明", 18, "2024001");
student.introduce();

🥦 西兰花警告:
ArkTS 中没有专门的struct关键字,简单的数据结构可以用interface定义,需要实例化的用class实现!别再找 struct 了 o(╯□╰)o

2.6 可选类型

Swift 写法:

// 可选类型
var optionalName: String? = "盐焗西兰花"
var optionalAge: Int?

// 解包
if let name = optionalName {
    print("Name: \(name)")
}

// 强制解包(危险!)
let forcedName = optionalName!

ArkTS 写法:

// 可选类型(用?表示)
let optionalName: string? = "盐焗西兰花";
let optionalAge: number?;

// 解包
if (optionalName != undefined) {
    console.log(`Name: ${optionalName}`);
}

// 空值合并运算符
let name = optionalName ?? "匿名用户";

🥦 西兰花小贴士:

  • ArkTS 的可选类型和 Swift 类似,但用undefined代替nil
  • 推荐使用空值合并运算符??代替强制解包,更安全!

3. ArkTS 特有的:声明式 UI

作为鸿蒙开发的核心,ArkTS 的声明式 UI 是 Swift 开发者需要重点学习的部分。其实这和 SwiftUI 的理念很像!

SwiftUI 写法:

struct ContentView: View {
    @State var count = 0

    var body: some View {
        VStack {
            Text("你点击了 \(count) 次")
                .font(.title)
            Button(action: {
                count += 1
            }) {
                Text("点击我")
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
        }
        .padding()
    }
}

ArkTS 写法:

@Entry
@Component
struct Index {
    // 状态管理
    @State count: number = 0;

    build() {
        Column() {
            Text(`你点击了 ${this.count} 次`)
                .fontSize(24)
            Button({
                type: ButtonType.Capsule,
                stateEffect: true
            }) {
                Text("点击我")
                    .fontSize(16)
                    .fontWeight(FontWeight.Medium)
                    .textAlign(TextAlign.Center)
                    .width(90)
                    .height(40)
            }
            .backgroundColor(0x007AFF)
            .onClick(() => {
                this.count++;
            })
        }
        .width('100%')
        .height('100%')
        .justifyContent(FlexAlign.Center)
        .alignItems(HorizontalAlign.Center)
    }
}

🥦 西兰花小贴士:

  • ArkTS 用@Entry@Component标记页面组件,相当于 SwiftUI 的View协议
  • @State状态管理和 SwiftUI 的@State几乎一样!
  • 布局组件用Column()/Row()代替VStack()/HStack()

4. 快速实战:写个计数器 Demo

现在咱们把上面的知识整合起来,写个完整的 ArkTS 计数器 demo!

// 导入必要的模块
import router from '@ohos.router';

// 页面入口
@Entry
@Component
struct CounterPage {
    // 状态管理
    @State count: number = 0;
    @State message: string = "Hello Swift开发者!";

    // 自定义方法
    private increment(): void {
        this.count++;
        if (this.count >= 10) {
            this.message = "哇,你超厉害!";
        }
    }

    private decrement(): void {
        if (this.count > 0) {
            this.count--;
        }
        if (this.count < 10) {
            this.message = "Hello Swift开发者!";
        }
    }

    // 页面构建
    build() {
        Column() {
            // 标题
            Text(this.message)
                .fontSize(28)
                .fontWeight(FontWeight.Bold)
                .margin({ bottom: 40 })

            // 计数器显示
            Text(`当前计数:${this.count}`)
                .fontSize(48)
                .fontWeight(FontWeight.Bold)
                .margin({ bottom: 60 })

            // 按钮组
            Row() {
                Button("-")
                    .width(80)
                    .height(80)
                    .fontSize(32)
                    .backgroundColor(0xFF3B30)
                    .onClick(() => this.decrement())

                Blank()
                    .width(60)

                Button("+")
                    .width(80)
                    .height(80)
                    .fontSize(32)
                    .backgroundColor(0x34C759)
                    .onClick(() => this.increment())
            }
        }
        .width('100%')
        .height('100%')
        .justifyContent(FlexAlign.Center)
        .alignItems(HorizontalAlign.Center)
    }
}

🥦 西兰花警告:
别忘记在 DevEco Studio 中创建项目时选择"Empty Ability"模板,然后把代码替换到Index.ets文件中!


5. 下一步:从 Swift 开发者到 ArkTS 大师

  1. 先跑通 Demo:把上面的计数器代码复制到 DevEco Studio,运行看看效果
  2. 学习声明式 UI:重点掌握 ArkTS 的布局组件和状态管理
  3. 熟悉 API:鸿蒙的 API 文档是个好东西,多看看_

📚 推荐资料:


我是盐焗西兰花,
一个正在把pod install炒成ohpm install的厨子_
不教理论,只给你能跑的代码和避坑指南。
下期见!🥦

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐