跳到主要内容

作为 Swift 开发者学习 Dart

本指南旨在利用您在学习 Dart 时的 Swift 编程知识。它展示了两种语言的关键相似之处和不同之处,并介绍了 Swift 中不存在的 Dart 概念。作为一名 Swift 开发者,Dart 可能会让您感到熟悉,因为这两种语言都共享许多概念。

Swift 和 Dart 都支持健全的空安全。两种语言默认都不允许变量为空。

与 Swift 类似,Dart 对集合泛型并发(使用 async/await)和扩展提供了类似的支持。

混入是 Dart 中的另一个概念,Swift 开发者可能不熟悉。与 Swift 类似,Dart 提供了 AOT(预先编译)编译。然而,Dart 也支持 JIT(即时编译)编译模式,以帮助进行各种开发方面的工作,例如增量重新编译或调试。有关更多信息,请查看 Dart 概览

约定和 Lint

#

Swift 和 Dart 都有 Lint 工具来强制执行标准约定。然而,虽然 Swift 有 SwiftLint 作为一个独立的工具,但 Dart 有官方的布局约定,并包含一个 Lint 工具,使合规性变得轻松。要自定义项目的 Lint 规则,请按照自定义静态分析说明进行操作。(请注意,Dart 和 Flutter 的 IDE 插件也提供了此功能。)

Dart 还提供了一个代码格式化程序,当从命令行或通过 IDE 运行 dart format 时,它可以自动格式化任何 Dart 项目。

有关 Dart 约定和 Lint 的更多信息,请查看 Effective DartLinter 规则

变量

#

与 Swift 相比,在 Dart 中声明和初始化变量有点不同。变量声明始终以变量的类型、var 关键字或 final 关键字开头。与 Swift 一样,Dart 支持类型推断,编译器会根据分配给变量的值推断类型

dart
// String-typed variable.
String name = 'Bob';

// Immutable String-typed variable.
final String name = 'Bob';

// This is the same as `String name = 'Bob';`
// since Dart infers the type to be String.
var name = 'Bob';

// And this is the same as `final String name = 'Bob';`.
final name = 'Bob';

每个 Dart 语句都以分号结尾,以指示语句的结束。您可以用显式类型替换 Dart 中的 var。但是,按照约定,当分析器可以隐式推断类型时,建议使用 var

dart
// Declare a variable first:
String name; 
// Initialize the variable later:
name = 'bob';
// Declare and initialize a variable at once with inference:
var name = 'bob';

上述 Dart 代码的 Swift 等效代码如下

swift
// Declare a variable first: 
var name: String
// Initialize the variable later
name = "bob"

// Declare and initialize a variable at once with inference:
var name = "bob"

在 Dart 中,当没有显式类型的变量在其声明后初始化时,其类型被推断为通用的 dynamic 类型。同样,当无法自动推断类型时,它默认设置为 dynamic 类型,这会消除所有类型安全。因此,Dart Lint 通过生成警告来阻止这种情况。如果您打算允许变量具有任何类型,则最好将其赋值给 Object? 而不是 dynamic

有关更多信息,请查看 Dart 语言之旅中的变量部分

Final

#

Dart 中的 final 关键字表示变量只能设置一次。这类似于 Swift 中的 let 关键字。

在 Dart 和 Swift 中,您都只能初始化 final 变量一次,可以在声明语句中或在初始化列表中进行。任何第二次尝试赋值都会导致编译时错误。以下两个代码片段都是有效的,但随后设置 name 会导致编译错误。

dart
final String name;
if (b1) {
  name = 'John';
} else {
  name = 'Jane';
}
swift
let name: String
if (b1) {
  name = "John"
} else {
  name = "Jane"
}

Const

#

除了 final 之外,Dart 还有 const 关键字。const 的一个好处是它在编译时被完全求值,并且在应用程序的生命周期内无法修改。

dart
const bar = 1000000; // Unit of pressure (dynes/cm2)
const double atm = 1.01325 * bar; // Standard atmosphere

在类级别定义的 const 变量需要标记为 static const

dart
class StandardAtmosphere {
  static const bar = 1000000; // Unit of pressure (dynes/cm2)
  static const double atm = 1.01325 * bar; // Standard atmosphere
}

const 关键字不仅用于声明常量变量;它还可以用于创建常量值

dart
var foo = const ['one', 'two', 'three'];
foo.add('four'); // Error: foo contains a constant value.
foo = ['apple', 'pear']; // This is allowed as foo itself isn't constant.
foo.add('orange'); // Allowed as foo no longer contains a constant value.

在上面的示例中,您不能更改 const 值(添加、更新或删除给定列表中的元素),但您可以为 foo 分配一个新值。在为 foo 分配一个新的(非常量)列表后,您可以添加、更新或删除列表的内容。

您还可以将常量值分配给 final 字段。您不能在常量上下文中使用 final 字段,但可以使用常量。例如

dart
final foo1 = const [1, 2, 3];
const foo2 = [1, 2, 3]; // Equivalent to `const [1, 2, 3]`
const bar2 = foo2; // OK
const bar1 = foo1; // Compile-time error, `foo1` isn't constant

您还可以定义 const 构造函数,使这些类成为不可变的(不变的),并使创建这些类的实例作为编译时常量成为可能。有关更多信息,请查看 const 构造函数

内置类型

#

Dart 在平台库中包含许多类型,例如

  • 基本值类型,如
    • 数字 (num, int, double)
    • 字符串 (String)
    • 布尔值 (bool)
    • 空值 (Null)
  • 集合
    • 列表/数组 (List)
    • 集合 (Set)
    • Map/字典 (Map)

有关更多信息,请查看 Dart 语言之旅中的内置类型

数字

#

Dart 定义了三种数字类型来保存数字

num
通用 64 位数字类型。
int
平台相关的整数类型。在原生代码中,它是 64 位二补码整数。在 Web 上,它是非分数 64 位浮点数。
double
64 位浮点数。

与 Swift 不同,没有用于无符号整数的特定类型。

所有这些类型也是 Dart API 中的类。intdouble 类型都共享 num 作为它们的父类

Object is the parent of num, which is the parent of int and double

由于数字值在技术上是类实例,因此它们可以方便地公开自己的实用程序函数。因此,例如,可以将 int 转换为 double,如下所示

dart
int intVariable = 3;
double doubleVariable = intVariable.toDouble();

在 Swift 中,使用专用初始化器可以实现相同的目的

swift
var intVariable: Int = 3
var doubleVariable: Double = Double(intVariable)

在字面量值的情况下,Dart 会自动将整数文字转换为 double 值。以下代码完全没问题

dart
double doubleValue = 3;

与 Swift 不同,在 Dart 中,您可以使用相等 (==) 运算符将整数值与 double 值进行比较,如下所示

dart
int intVariable = 3;
double doubleVariable = 3.0;
print(intVariable == doubleVariable); // true

此代码输出 true。但是,在 Dart 中,Web 和原生平台之间的底层数字实现是不同的。Dart 中的数字页面详细介绍了这些差异,并展示了如何编写代码以使差异无关紧要。

字符串

#

与 Swift 一样,Dart 使用 String 类型表示一系列字符,尽管 Dart 不支持表示单个字符的 Character 类型。可以使用单引号或双引号定义 String,但是,首选单引号

dart
String c = 'a'; // There isn't a specialized "Character" type
String s1 = 'This is a String';
String s2 = "This is also a String";
swift
let c: Character = "a"
let s1: String = "This is a String"
let s2: String = "This is also a String"

转义特殊字符

#

Dart 中转义特殊字符类似于 Swift(和大多数其他语言)。要包含特殊字符,请使用反斜杠字符转义它们。

以下代码显示了一些示例

dart
final singleQuotes = 'I\'m learning Dart'; // I'm learning Dart
final doubleQuotes = "Escaping the \" character"; // Escaping the " character
final unicode = '\u{1F60E}'; // 😎,  Unicode scalar U+1F60E

请注意,也可以直接使用 4 位十六进制值(例如,\u2665),但是,花括号也有效。有关使用 Unicode 字符的更多信息,请查看 Dart 语言之旅中的符文和字素簇

字符串连接和多行声明

#

在 Dart 和 Swift 中,您都可以转义多行字符串中的换行符,这使您可以保持源代码更易于阅读,但仍以单行输出 String。Dart 有几种定义多行字符串的方法

  1. 使用隐式字符串连接:任何相邻的字符串文字都会自动连接,即使它们分布在多行上

    dart
    final s1 = 'String '
      'concatenation'
      " even works over line breaks.";
  2. 使用多行字符串文字:当在字符串的任一侧使用三个引号(单引号或双引号)时,文字可以跨越多行

    dart
    final s2 = '''You can create
    multiline strings like this one.''';
    
    final s3 = """This is also a
    multiline string.""";
  3. Dart 还支持使用 + 运算符连接字符串。这适用于字符串文字和字符串变量

    dart
    final name = 'John';
    final greeting = 'Hello ' + name + '!';

字符串插值

#

使用 ${<expression>} 语法将表达式插入到字符串文字中。Dart 对此进行了扩展,允许在表达式是单个标识符时省略花括号

dart
var food = 'bread';
var str = 'I eat $food'; // I eat bread
var str = 'I eat ${bakery.bestSeller}'; // I eat bread

在 Swift 中,您可以通过将变量或表达式用括号括起来并以反斜杠作为前缀来获得相同的结果

swift
let s = "string interpolation"
let c = "Swift has \(s), which is very handy."

原始字符串

#

与 Swift 中一样,您可以在 Dart 中定义原始字符串。原始字符串忽略转义字符并包含字符串中存在的任何特殊字符。您可以通过在字符串文字前加上字母 r 在 Dart 中执行此操作,如下例所示。

dart
// Include the \n characters.
final s1 = r'Includes the \n characters.';
// Also includes the \n characters.
final s2 = r"Also includes the \n characters.";

final s3 = r'''
  The \n characters are also included
  when using raw multiline strings.
  ''';
final s4 = r"""
  The \n characters are also included
  when using raw multiline strings.
  """;
swift
let s1 = #"Includes the \n characters."#
let s2 = #"""
  The \n characters are also included
  when using raw multiline strings.
  """#

相等性

#

与 Swift 中一样,Dart 的相等运算符 (==) 比较两个字符串是否相等。如果两个字符串包含相同的代码单元序列,则它们相等。

dart
final s1 = 'String '
  'concatenation'
  " works even over line breaks.";
assert(s1 ==
  'String concatenation works even over '
  'line breaks.');

常用 API

#

Dart 为字符串提供了几个常用 API。例如,Dart 和 Swift 都允许您使用 isEmpty 检查字符串是否为空。还有其他方便的方法,例如 toUpperCasetoLowerCase。有关更多信息,请查看 Dart 语言之旅中的字符串

布尔值

#

布尔值在 Dart (bool) 和 Swift (Bool) 中都表示二进制值。

空安全

#

Dart 强制执行健全的空安全。默认情况下,类型不允许空值,除非标记为可为空。Dart 使用问号 (?) 在类型末尾指示这一点。这类似于 Swift 的可选项

空感知运算符

#

Dart 支持多个处理可空性的运算符。空值合并运算符 (??) 和可选链运算符 (?.) 在 Dart 中可用,并且与 Swift 中的操作方式相同

dart
a = a ?? b;
swift
let str: String? = nil
let count = str?.count ?? 0

此外,Dart 还提供了级联运算符 (?..) 的空安全版本。当目标表达式解析为 null 时,此运算符会忽略任何操作。Dart 还提供了空值赋值运算符 (??=),Swift 中没有。如果具有可空类型的变量的当前值为 null,则此运算符会为该变量赋值。表示为 a ??= b;,它充当以下代码的简写

dart
a = a ?? b;

// Assign b to a if a is null; otherwise, a stays the same
a ??= b;
swift
a = a ?? b

! 运算符(也称为“强制解包”)

#

在可以安全地假设可空变量或表达式实际上是非空的情况下,可以告诉编译器抑制任何编译时错误。这是通过使用后缀 ! 运算符完成的,方法是将其作为后缀放在表达式的后面。(不要将此与 Dart 的“非”运算符混淆,后者使用相同的符号)

dart
int? a = 5;

int b = a; // Not allowed.
int b = a!; // Allowed.

在运行时,如果 a 结果为空,则会发生运行时错误。

?. 运算符类似,在访问对象上的属性或方法时使用 ! 运算符

dart
myObject!.someProperty;
myObject!.someMethod();

如果 myObject 在运行时为 null,则会发生运行时错误。

延迟字段

#

late 关键字可以分配给类字段,以指示它们稍后初始化,同时保持非可空。这类似于 Swift 的“隐式解包可选项”。这对于在变量在初始化之前从未被观察到的情况下很有用,允许稍后初始化它。非可空 late 字段不能在稍后分配空值。此外,非可空 late 字段在初始化之前被观察到时会抛出运行时错误,这是您希望在行为良好的应用程序中避免的情况。

dart
// Using null safety:
class Coffee {
  late String _temperature;

  void heat() { _temperature = 'hot'; }
  void chill() { _temperature = 'iced'; }

  String serve() => _temperature + ' coffee';
}

在这种情况下,_temperature 仅在调用 heat()chill() 之后初始化。如果在其他函数之前调用 serve(),则会发生运行时异常。请注意,_temperature 永远不能为 null

当将 late 关键字与初始化器结合使用时,您也可以使用它来延迟初始化

dart
class Weather {
  late int _temperature = _readThermometer();
}

在这种情况下,_readThermometer() 仅在首次访问该字段时运行,而不是在初始化时运行。

Dart 中的另一个优点是使用 late 关键字来延迟 final 变量的初始化。虽然您不必在将 final 变量标记为 late 时立即初始化它,但它仍然只能初始化一次。第二次赋值会导致运行时错误。

dart
late final int a;
a = 1;
a = 2; // Throws a runtime exception because
       // "a" is already initialized.

函数

#

Swift 使用 main.swift 文件作为应用程序的入口点。Dart 使用 main 函数作为应用程序的入口点。每个程序都必须有一个 main 函数才能执行。例如

dart
void main() {
  // main function is the entry point
  print("hello world");
}
swift
// main.swift file is the entry point
print("hello world")

Dart 不支持 Tuples(尽管 pub.dev 上有几个元组包可用)。如果函数需要返回多个值,您可以将它们包装在集合中,例如列表、集合或 Map,或者您可以编写一个包装类,可以返回包含这些值的实例。有关更多信息,请参阅关于集合的部分。

异常和错误处理

#

与 Swift 中一样,Dart 的函数和方法都支持处理异常错误。Dart 错误通常表示程序员的错误或系统故障,如堆栈溢出。Dart 错误不应该被捕获。另一方面,Dart 异常表示可恢复的故障,旨在被捕获。例如,在运行时,代码可能尝试访问流媒体源,但却收到一个异常,如果未捕获该异常,则会导致应用程序终止。您可以通过将函数调用包装在 try-catch 块中来管理 Dart 中的异常。

dart
try {
  // Create audio player object
  audioPlayer = AVAudioPlayer(soundUrl);
            
  // Play the sound
  audioPlayer.play();
}
catch {
  // Couldn't create audio player object, log the exception
  print("Couldn't create the audio player for file $soundFilename");
}

类似地,Swift 使用 do-try-catch 块。例如

swift
do {
  // Create audio player object
  audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
            
  // Play the sound
  audioPlayer?.play()
}
catch {
  // Couldn't create audio player object, log the error
  print("Couldn't create the audio player for file \(soundFilename)")
}

您可以在同步和异步 Dart 代码中使用 try-catch 块。有关更多信息,请参阅 ErrorException 类的文档。

参数

#

与 Swift 类似,Dart 在其函数中支持命名参数。但是,与 Swift 不同,这些在 Dart 中不是默认设置。Dart 中的默认参数类型是位置参数。

dart
int multiply(int a, int b) {
  return a * b;
}

Swift 中的等效代码在参数前加上下划线,以消除对参数标签的需求。

swift
func multiply(_ a: Int, _ b: Int) -> Int {
  return a * b
}

在 Dart 中创建命名参数时,请在位置参数之后的单独花括号块中定义它们

dart
int multiply(int a, int b, {int c = 1, int d = 1}) {
  return a * b * c * d;
}

// Calling a function with both required and named parameters
multiply(3, 5); // 15
multiply(3, 5, c: 2); // 30
multiply(3, 5, d: 3); // 45
multiply(3, 5, c: 2, d: 3); // 90
swift
// The Swift equivalent
func multiply(_ a: Int, _ b: Int, c: Int = 1, d: Int = 1) -> Int {
  return a * b * c * d
}

命名参数必须包含以下项之一

  • 默认值
  • 类型末尾的 ?,将类型设置为可空
  • 变量类型之前的关键字 required

要了解有关可空类型的更多信息,请查看空安全

要在 Dart 中将命名参数标记为必需,您必须在其前面加上 required 关键字

dart
int multiply(int a, int b, { required int c }) {
  return a * b * c;
}
// When calling the function, c has to be provided
multiply(3, 5, c: 2);

第三种参数类型是可选位置参数。顾名思义,这些参数类似于默认位置参数,但在调用函数时可以省略。它们必须列在任何必需的位置参数之后,并且不能与命名参数结合使用。

dart
int multiply(int a, int b, [int c = 1, int d = 1]) {
  return a * b * c * d;
}
// Calling a function with both required and optional positioned parameters.
multiply(3, 5); // 15
multiply(3, 5, 2); // 30
multiply(3, 5, 2, 3); // 90
swift
// The Swift equivalent
func multiply(_ a: Int, _ b: Int, _ c: Int = 1, _ d: Int = 1) -> Int {
  return a * b * c * d
}

与命名参数一样,可选位置参数必须具有默认值或可空类型。

一等函数

#

与 Swift 中一样,Dart 函数也是一等公民,这意味着它们被视为任何其他对象。例如,以下代码显示了如何从函数返回函数

dart
typedef int MultiplierFunction(int value);
// Define a function that returns another function
MultiplierFunction multiplyBy(int multiplier) {
  return (int value) {
    return value * multiplier;
  };
}
// Call function that returns new function
MultiplierFunction multiplyByTwo = multiplyBy(2);
// Call the new function
print(multiplyByTwo(3)); // 6
swift
// The Swift equivalent of the Dart function below
// Define a function that returns a closure
typealias MultiplierFunction = (Int) -> (Int)

func multiplyBy(_ multiplier: Int) -> MultiplierFunction {
  return { $0 * multiplier} // Returns a closure
}

// Call function that returns a function
let multiplyByTwo = multiplyBy(2)
// Call the new function
print(multiplyByTwo(3)) // 6

匿名函数

#

匿名函数 在 Dart 中的工作方式与 Swift 中的闭包几乎相同,只是语法上有所不同。与命名函数一样,您可以像传递任何其他值一样传递匿名函数。例如,您可以将匿名函数存储在变量中,将其作为参数传递给另一个函数,或从另一个函数返回它们。

Dart 有两种声明匿名函数的方法。第一种方法使用花括号,其工作方式与任何其他函数相同。它允许您使用多行,并且对于要返回的任何值,它都需要一个 return 语句。

dart
// Multi line anonymous function
[1,2,3].map((element) { 
  return element * 2; 
}).toList(); // [2, 4, 6]
swift
  // Swift equivalent anonymous function
  [1, 2, 3].map { $0 * 2 }

另一种方法使用箭头函数,以其语法中使用的类似箭头的符号命名。当您的函数体仅包含单个表达式并且返回值时,可以使用此简写语法。这省略了对任何花括号或 return 语句的需求,因为这些都是隐含的。

dart
// Single-line anonymous function
[1,2,3].map((element) => element * 2).toList(); // [2, 4, 6]

箭头语法或花括号之间的选择适用于任何函数,而不仅仅是匿名函数。

dart
multiply(int a, int b) => a * b;

multiply(int a, int b) {
  return a * b;
}

生成器函数

#

Dart 支持生成器函数,该函数返回一个可迭代的项目集合,这些项目是延迟构建的。使用 yield 关键字将项目添加到最终的可迭代对象,或使用 yield* 添加整个项目集合。

以下示例显示了如何编写基本生成器函数

dart
Iterable<int> listNumbers(int n) sync* {
  int k = 0;
  while (k < n) yield k++;
}

// Returns an `Iterable<int>` that iterates
// through 0, 1, 2, 3, and 4.
print(listNumbers(5));

Iterable<int> doubleNumbersTo(int n) sync* {
  int k = 0;
  while (k < n) { 
    yield* [k, k]; 
    k++;
  }
}

print(doubleNumbersTo(3)); // Returns an iterable with [0, 0], [1, 1], and [2, 2].

这是一个 同步 生成器函数的示例。您还可以定义 异步 生成器函数,该函数返回 Stream 而不是可迭代对象。在并发部分了解更多信息。

语句

#

本节介绍 Dart 和 Swift 之间语句的异同。

控制流 (if/else, for, while, switch)

#

Dart 中的所有控制流语句的工作方式都与其 Swift 对应项类似,只是语法上有一些差异。

if

#

与 Swift 不同,Dart 中的 if 语句需要在条件周围加上括号。虽然 Dart 风格指南建议在控制流语句周围使用花括号(如下所示),但当您的 if 语句没有 else 子句并且整个 if 语句适合一行时,如果您愿意,可以省略花括号。

dart
var a = 1;
// Parentheses for conditions are required in Dart.
if (a == 1) {
  print('a == 1');
} else if (a == 2) {
  print('a == 2');
} else {
  print('a != 1 && a != 2');
}

// Curly braces are optional for single line `if` statements.
if (a == 1) print('a == 1');
swift
let a = 1;
if a == 1 {
  print("a == 1")
} else if a == 2 {
  print("a == 2")
} else {
  print("a != 1 && a != 2")
}

for(-in)

#

在 Swift 中,for 循环仅用于循环遍历集合。要多次循环遍历一段代码,Swift 允许您循环遍历一个范围。Dart 不支持用于定义范围的语法,但除了循环遍历集合的 for-in 之外,还包括一个标准 for 循环。

Dart 的 for-in 循环与其 Swift 对应项的工作方式类似,并且它可以循环遍历任何作为 Iterable 的值,如下面的 List 示例所示

dart
var list = [0, 1, 2, 3, 4];
for (var i in list) {
  print(i);
}
swift
let array = [0, 1, 2, 3, 4]
for i in array {
  print(i)
}

Dart 没有像 Swift 那样具有允许您循环遍历 Map 的 for-in 循环的任何特殊语法,Swift 具有字典的语法。为了实现类似的效果,您可以将 Map 的条目提取为 Iterable 类型。或者,您可以使用 Map.forEach

dart
Map<String, int> dict = {
  'Foo': 1,
  'Bar': 2
};
for (var e in dict.entries) {
  print('${e.key}, ${e.value}');
}
dict.forEach((key, value) {
  print('$key, $value');
});
swift
var dict:[String:Int] = [
  "Foo":1,
  "Bar":2
]
for (key, value) in dict {
   print("\(key),\(value)")
}

运算符

#

与 Swift 不同,Dart 不允许添加新运算符,但它允许您使用 operator 关键字重载现有运算符。例如

dart
class Vector {
  final double x;
  final double y;
  final double z;

  Vector operator +(Vector v) {
    return Vector(x: x + v.x, y: y + v.y, z: z+v.z);
  }
}
swift
struct Vector {
  let x: Double
  let y: Double
  let z: Double
}

func +(lhs: Vector, rhs: Vector) -> Vector {
  return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z)
}

...

算术运算符

#

在大多数情况下,算术运算符在 Swift 和 Dart 中的行为相同,但除法运算符 (/) 除外。在 Swift(和许多其他编程语言)中,let x = 5/2 的结果是 2(整数)。在 Dart 中,int x = 5/2, 的结果是 2.5(浮点值)。要获得整数结果,请使用 Dart 的截断除法运算符 (~/)。

虽然 ++ 运算符在早期版本的 Swift 中存在,但它们已在 Swift 3.0 中被删除。Dart 等效项的操作方式相同。例如

dart
assert(2 + 3 == 5);
assert(2 - 3 == -1);
assert(2 * 3 == 6);
assert(5 / 2 == 2.5); // Result is a double
assert(5 ~/ 2 == 2); // Result is an int
assert(5 % 2 == 1); // Remainder

a = 0;
b = ++a; // Increment a before b gets its value.
assert(a == b); // 1 == 1

a = 0;
b = a++; // Increment a AFTER b gets its value.
assert(a != b); // 1 != 0

类型测试运算符

#

测试运算符的实现在这两种语言之间略有不同。

含义Dart 运算符Swift 等效项
类型转换(如下所述)expr as Texpr as! T
expr as? T
如果对象具有指定的类型,则为 Trueexpr is Texpr is T
如果对象不具有指定的类型,则为 Trueexpr is! T!(expr is T)

如果 objT 指定类型的子类型,则 obj is T 的结果为 true。例如,obj is Object? 始终为 true。

使用类型转换运算符将对象强制转换为特定类型 — 当且仅当 — 您确定该对象属于该类型时。例如

dart
(person as Employee).employeeNumber = 4204583;

Dart 只有一个单类型转换运算符,其行为类似于 Swift 的 as! 运算符。Swift 的 as? 运算符没有等效项。

swift
(person as! Employee).employeeNumber = 4204583;

如果您不确定对象是否为类型 T,请在使用对象之前使用 is T 进行检查。

在 Dart 中,类型提升会在 if 语句的范围内更新局部变量的类型。这也适用于空检查。提升仅适用于局部变量,而不适用于实例变量。

dart
if (person is Employee) {
  person.employeeNumber = 4204583;
}
swift
// Swift requires the variable to be cast.
if let person = person as? Employee {
  print(person.employeeNumber) 
}

逻辑运算符

#

逻辑运算符(如 AND (&&)、OR (||) 和 NOT (!))在这两种语言中都是相同的。例如

dart
if (!done && (col == 0 || col == 3)) {
  // ...Do something...
}

按位和移位运算符

#

按位运算符在这两种语言中基本相同。

例如

dart
final value = 0x22;
final bitmask = 0x0f;

assert((value & bitmask) == 0x02); // AND
assert((value & ~bitmask) == 0x20); // AND NOT
assert((value | bitmask) == 0x2f); // OR
assert((value ^ bitmask) == 0x2d); // XOR
assert((value << 4) == 0x220); // Shift left
assert((value >> 4) == 0x02); // Shift right
assert((-value >> 4) == -0x03); // Shift right // Result may differ on the web

条件运算符

#

Dart 和 Swift 都包含一个条件运算符 (?:),用于评估可能需要 if-else 语句的表达式

dart
final displayLabel = canAfford ? 'Please pay below' : 'Insufficient funds';
swift
let displayLabel = canAfford ?  "Please pay below" : "Insufficient funds"

级联(.. 运算符)

#

与 Swift 不同,Dart 支持使用级联运算符进行级联。这允许您在单个对象上链式调用多个方法或属性赋值。

以下示例显示了设置多个属性的值,然后在新构造的对象上调用多个方法,所有这些都在使用级联运算符的单个链中完成

dart
Animal animal = Animal()
  ..name = 'Bob'
  ..age = 5
  ..feed()
  ..walk();

print(animal.name); // "Bob"
print(animal.age); // 5
swift
var animal = Animal()
animal.name = "Bob"
animal.age = 5
animal.feed()
animal.walk()

print(animal.name)
print(animal.age)

集合

#

本节介绍 Swift 中的一些集合类型,以及它们与 Dart 中等效类型的比较。

列表

#

List 字面量在 Dart 中的定义方式与 Swift 中的数组相同,使用方括号并用逗号分隔。两种语言之间的语法非常相似,但是有一些细微的差异,如下例所示

dart
final List<String> list1 = <String>['one', 'two', 'three']; // Initialize list and specify full type
final list2 = <String>['one', 'two', 'three']; // Initialize list using shorthand type
final list3 = ['one', 'two', 'three']; // Dart can also infer the type
swift
var list1: Array<String> = ["one", "two", "three"] // Initialize array and specify the full type
var list2: [String] = ["one", "two", "three"] // Initialize array using shorthand type
var list3 = ["one", "two", "three"] // Swift can also infer the type

以下代码示例概述了您可以在 Dart List 上执行的基本操作。第一个示例显示了如何使用 index 运算符从列表中检索值

dart
final fruits = ['apple', 'orange', 'pear'];
final fruit = fruits[1];

要将值添加到列表的末尾,请使用 add 方法。要添加另一个 List,请使用 addAll 方法

dart
final fruits = ['apple', 'orange', 'pear'];
fruits.add('peach');
fruits.addAll(['kiwi', 'mango']);

有关完整的 List API,请参阅 List文档。

不可修改

#

将数组分配给常量(Swift 中的 let)会使数组不可变,这意味着其大小和内容都无法更改。您也不能将新数组分配给常量。

在 Dart 中,这有点不同,并且根据您的需求,您有几个选项可供选择

  • 如果列表是编译时常量并且不应修改,请使用 const 关键字
    const fruits = ['apple', 'orange', 'pear'];
  • 将列表分配给 final 字段。这意味着列表本身不必是编译时常量,并确保该字段不能被另一个列表覆盖。但是,它仍然允许修改列表的大小或内容
    final fruits = ['apple', 'orange', 'pear'];
  • 使用不可修改的构造函数(如下例所示)创建一个 final List。这将创建一个无法更改大小或内容的 List,使其行为就像 Swift 中的常量 Array
dart
final fruits = List<String>.unmodifiable(['apple', 'orange', 'pear']);
swift
let fruits = ["apple", "orange", "pear"]

展开运算符

#

Dart 中另一个有用的特性是展开运算符 (...) 和空感知展开运算符 (...?),它们提供了一种简洁的方式将多个值插入到集合中。

例如,你可以使用展开运算符 (...) 将一个列表的所有值插入到另一个列表中,如下所示

dart
final list = [1, 2, 3];
final list2 = [0, ...list]; // [ 0, 1, 2, 3 ]
assert(list2.length == 4);

虽然 Swift 没有展开运算符,但上面第 2 行的等效代码如下

swift
let list2 = [0] + list

如果展开运算符右侧的表达式可能为 null,你可以使用空感知展开运算符 (...?) 来避免异常

dart
List<int>? list;
final list2 = [0, ...?list]; //[ 0 ]
assert(list2.length == 1);
swift
let list2 = [0] + list ?? []

集合

#

Dart 和 Swift 都支持使用字面量定义 Set。Set 的定义方式与列表相同,但使用花括号而不是方括号。Set 是无序集合,仅包含唯一项。这些项的唯一性是使用哈希码实现的,这意味着对象需要哈希值才能存储在 Set 中。每个 Dart 对象都包含一个哈希码,而在 Swift 中,你需要显式应用 Hashable 协议,对象才能存储在 Set 中。

以下代码片段显示了在 Dart 和 Swift 中初始化 Set 的区别

dart
final abc = {'a', 'b', 'c'};
swift
var abc: Set<String> = ["a", "b", "c"]

你不能通过指定空花括号 ({}) 在 Dart 中创建一个空 set;这将导致创建一个空 Map。要创建一个空 Set,请在 {} 声明之前加上类型参数,或将 {} 赋值给类型为 Set 的变量

dart
final names = <String>{};
Set<String> alsoNames = {}; // This works, too.
// final names = {}; // Creates an empty map, not a set.

不可修改

#

List 类似,Set 也有一个不可修改的版本。例如

dart
final abc = Set<String>.unmodifiable(['a', 'b', 'c']);
swift
let abc: Set<String> = ["a", "b", "c"]

Map

#

Dart 中的 Map 类型可以与 Swift 中的 Dictionary 类型进行比较。这两种类型都关联键和值。这些键和值可以是任何类型的对象。每个键只出现一次,但你可以多次使用相同的值。

在两种语言中,字典都基于哈希表,这意味着键需要是可哈希的。在 Dart 中,每个对象都包含一个哈希值,而在 Swift 中,你需要显式应用 Hashable 协议,对象才能存储在 Dictionary 中。

以下是一些使用字面量创建的简单 MapDictionary 示例

dart
final gifts = {
 'first': 'partridge',
 'second': 'turtle doves',
 'fifth': 'golden rings',
};

final nobleGases = {
 2: 'helium',
 10: 'neon',
 18: 'argon',
};
swift
let gifts = [
   "first": "partridge",
   "second": "turtle doves",
   "fifth": "golden rings",
]

let nobleGases = [
   2: "helium",
   10: "neon",
   18: "argon",
]

以下代码示例概述了你可以在 Dart Map 上执行的基本操作。第一个示例展示了如何使用 key 运算符从 Map 中检索值

dart
final gifts = {'first': 'partridge'};
final gift = gifts['first']; // 'partridge'

使用 containsKey 方法检查键是否已存在于 Map

dart
final gifts = {'first': 'partridge'};
assert(gifts.containsKey('fifth')); // false

使用索引赋值运算符 ([]=) 在 Map 中添加或更新条目。如果 Map 尚不包含该键,则会添加该条目。如果该键已存在,则会更新该条目的值

dart
final gifts = {'first': 'partridge'};
gifts['second'] = 'turtle'; // Gets added
gifts['second'] = 'turtle doves'; // Gets updated

要从 Map 中删除条目,请使用 remove 方法;要删除所有满足给定测试的条目,请使用 removeWhere 方法

dart
final gifts = {'first': 'partridge'};
gifts.remove('first');
gifts.removeWhere((key, value) => value == 'partridge');

#

Dart 没有定义接口类型——任何类都可以用作接口。如果你只想引入一个接口,请创建一个没有具体成员的抽象类。要更详细地了解这些类别,请查看抽象类隐式接口扩展类部分中的文档。

Dart 不提供对值类型的支持。正如内置类型部分中提到的,Dart 中的所有类型都是引用类型(即使是原始类型),这意味着 Dart 不提供 struct 关键字。

枚举

#

枚举类型,通常称为枚举或 enums,是一种特殊的类,用于表示固定数量的常量值。枚举类型长期以来一直是 Dart 语言的一部分,但 Dart 2.17 添加了对成员的增强枚举支持。这意味着你可以添加保存状态的字段、设置该状态的构造函数、具有功能的方法,甚至覆盖现有成员。有关更多信息,请查看 Dart 语言之旅中的声明增强枚举

构造函数

#

Dart 的类构造函数的工作方式与 Swift 中的类初始化器类似。但是,在 Dart 中,它们为设置类属性提供了更多功能。

标准构造函数

#

标准类构造函数在声明和调用方面都与 Swift 初始化器非常相似。Dart 使用完整的类名而不是 init 关键字。new 关键字曾经是创建新类实例所必需的,但现在是可选的,不再推荐使用。

dart
class Point {
  double x = 0;
  double y = 0;

  Point(double x, double y) {
    // There's a better way to do this in Dart, stay tuned.
    this.x = x;
    this.y = y;
  }
}

// Create a new instance of the Point class
Point p = Point(3, 5);

构造函数参数

#

由于在构造函数中编写代码来分配所有类字段通常非常冗余,因此 Dart 提供了一些语法糖来简化此操作

dart
class Point {
  double x;
  double y;

  // Syntactic sugar for setting x and y
  // before the constructor body runs.
  Point(this.x, this.y);
}

// Create a new instance of the Point class
Point p = Point(3, 5);

与函数类似,构造函数也可以接受可选的位置参数或命名参数

dart
class Point {
  ...
  // With an optional positioned parameter
  Point(this.x, [this.y = 0]);
  // With named parameters
  Point({required this.y, this.x = 0});
  // With both positional and named parameters
  Point(int x, int y, {int scale = 1}) {
    ...
  }
  ...
}

初始化列表

#

你还可以使用初始化列表,它在构造函数参数中使用 this 直接设置任何字段之后运行,但在构造函数体之前运行

dart
class Point {
  ...
  Point(Map<String, double> json)
      : x = json['x']!,
        y = json['y']! {
    print('In Point.fromJson(): ($x, $y)');
  }
  ...
}

初始化列表是使用断言的好地方。

命名构造函数

#

与 Swift 不同,Dart 允许类拥有多个构造函数,允许你对其进行命名。你可以选择使用一个未命名的构造函数,但任何额外的构造函数都必须命名。一个类也可以只有命名构造函数。

dart
class Point {
  double x;
  double y;

  Point(this.x, this.y);

  // Named constructor
  Point.fromJson(Map<String, double> json)
      : x = json['x']!,
        y = json['y']!;
}

Const 构造函数

#

当你的类实例始终是不可变的(不变的)时,你可以通过添加 const 构造函数来强制执行此操作。删除 const 构造函数对于使用你的类的人来说是一个重大更改,因此请谨慎使用此功能。将构造函数定义为 const 使类变为不可修改:类中的所有非静态字段都必须标记为 final

dart
class ImmutablePoint {
  final double x, y;

  const ImmutablePoint(this.x, this.y);
}

这也意味着你可以将该类用作常量值,使对象成为编译时常量

dart
const ImmutablePoint origin = ImmutablePoint(0, 0);

构造函数重定向

#

你可以从其他构造函数调用构造函数,例如,为了防止代码重复或为参数添加额外的默认值

dart
class Point {
  double x, y;

  // The main constructor for this class.
  Point(this.x, this.y);

  // Delegates to the main constructor.
  Point.alongXAxis(double x) : this(x, 0);
}

工厂构造函数

#

当你不不需要创建新的类实例时,可以使用工厂构造函数。一个例子是如果可以返回缓存的实例

dart
class Logger {
  static final Map<String, Logger> _cache =
    <String, Logger>{};
  
  final String name;
  
  // Factory constructor that returns a cached copy,
  // or creates a new one if it's not yet available.
  factory Logger(String name)=> _cache[name] ??= Logger._internal(name);
  // Private constructor used only in this library
  Logger._internal(this.name);
}

方法

#

在 Dart 和 Swift 中,方法都是为对象提供行为的函数。

dart
void doSomething() { // This is a function
 // Implementation..
}

class Example {
 void doSomething() { // This is a method
   // Implementation..
 }
}
swift
func doSomething() { // This is a function
  // Implementation..
}

class Example {
  func doSomething() { // This is a method
    // Implementation..
  }
}

Getter 和 Setter

#

你可以通过在字段名称前加上 getset 关键字来定义 getter 和 setter。你可能还记得,每个实例字段都有一个隐式 getter,以及一个 setter(如果适用)。在 Swift 中,语法略有不同,因为 getset 关键字需要在属性语句内部定义,并且只能定义为语句,而不是表达式

dart
class Rectangle {
  double left, top, width, height;

  Rectangle(this.left, this.top, this.width, this.height);

  // Define two calculated properties: right and bottom.
  double get right => left + width;
  set right(double value) => width = value - left;

  double get bottom => top + height;
  set bottom(double value) => height = value - top;
}
swift
class Rectangle {
 var left, top, width, height: Double;

 init(left: Double, top: Double, width: Double, height: Double) {
   self.left = left
   self.top = top
   self.width = width
   self.height = height
 }

 // Define two calculated properties: right and bottom.
 var right: Double {
   get {
     return left + width
   }
   set { width = newValue - left }
 }

 var bottom: Double {
   get {
     return top + height
   }
   set { height = newValue - top }
 }
}

抽象类

#

Dart 具有抽象类的概念,Swift 不支持该概念。抽象类不能直接实例化,只能被子类化。这使得抽象类对于定义接口很有用(类似于 Swift 中的协议)。

抽象类通常包含抽象方法,这些方法是没有实现的方法声明。非抽象子类被迫覆盖这些方法并提供适当的实现。抽象类也可以包含具有默认实现的方法。子类继承此实现,如果它们在扩展抽象类时没有覆盖这些方法。

要定义抽象类,请使用 abstract 修饰符。以下示例声明了一个抽象类,该类具有一个抽象方法和一个包含默认实现的方法

dart
// This class is declared abstract and thus can't be instantiated.
abstract class AbstractContainer {
  void updateChildren(); // Abstract method.

  // Method with default implementation.
  String toString() => "AbstractContainer";
}

隐式接口

#

在 Dart 语言中,每个类都隐式定义一个接口,其中包含该类以及它实现的任何接口的所有实例成员。如果你想创建一个类 A,它支持类 B 的 API 而不继承 B 的实现,则类 A 应该实现 B 接口。

与 Dart 不同,Swift 类不隐式定义接口。接口需要显式定义为协议,并由开发人员实现。

一个类可以实现一个或多个接口,然后提供接口所需的 API。Dart 和 Swift 实现接口的方式不同。例如

dart
abstract class Animal {
  int getLegs();
  void makeNoise();
}

class Dog implements Animal {
  @override
  int getLegs() => 4;

  @override
  void makeNoise() => print('Woof woof');
}
swift
protocol Animal {
   func getLegs() -> Int;
   func makeNoise()
}

class Dog: Animal {
  func getLegs() -> Int {
    return 4;
  }

  func makeNoise() {
    print("Woof woof"); 
  }
}

扩展类

#

Dart 中的类继承与 Swift 非常相似。在 Dart 中,你可以使用 extends 创建子类,使用 super 引用超类

dart
abstract class Animal {
  // Define constructors, fields, methods...
}

class Dog extends Animal {
  // Define constructors, fields, methods...
}
swift
class Animal {
  // Define constructors, fields, methods...
}

class Dog: Animal {
  // Define constructors, fields, methods...
}

混入

#

混入允许你的代码在类之间共享功能。你可以在类中使用混入的字段和方法,就像它们是类的一部分一样使用它们的功能。一个类可以使用多个混入——当多个类共享相同的功能时,这非常有用——而无需彼此继承或共享共同的祖先。

虽然 Swift 不支持混入,但如果你编写一个协议以及一个为协议中指定的方法提供默认实现的扩展,则可以近似实现此功能。这种方法的主要问题是,与 Dart 不同,这些协议扩展不维护自己的状态。

你可以像声明普通类一样声明混入,只要它不扩展除 Object 之外的任何类并且没有构造函数。使用 with 关键字向类添加一个或多个逗号分隔的混入。

以下示例显示了如何在 Dart 中实现此行为,以及如何在 Swift 中复制类似的行为

dart
abstract class Animal {}

// Defining the mixins
mixin Flyer {
  fly() => print('Flaps wings');
}
mixin Walker {
  walk() => print('Walks legs');
}
  
class Bat extends Animal with Flyer {}
class Goose extends Animal with Flyer, Walker {}
class Dog extends Animal with Walker {}

// Correct calls
Bat().fly();
Goose().fly();
Goose().walk(); 
Dog().walk();

// Incorrect calls
Bat().walk(); // Not using the Walker mixin
Dog().fly(); // Not using the Flyer mixin
class Animal {
}
swift
// Defining the "mixins"
protocol Flyer {
  func fly()
}

extension Flyer {
  func fly() {
    print("Flaps wings")
  }
}

protocol Walker {
  func walk()
}

extension Walker {
  func walk() {
    print("Walks legs")
  }
}

class Bat: Animal, Flyer {}
class Goose: Animal, Flyer, Walker {}
class Dog: Animal, Walker {}

// Correct calls
Bat().fly();
Goose().fly();
Goose().walk();
Dog().walk();

// Incorrect calls
Bat().walk(); // `bat` doesn't have the `walk` method
Dog().fly(); // "dog" doesn't have the `fly` method

class 关键字替换为 mixin 可防止混入被用作普通类。

dart
mixin Walker {
  walk() => print('Walks legs');
}

// Impossible, as Walker is no longer a class.
class Bat extends Walker {}

由于你可以使用多个混入,因此当在同一个类上使用时,它们的方法或字段可能会相互重叠。它们甚至可以与使用它们的类或该类的超类重叠。为了解决这个问题,Dart 将它们堆叠在一起,因此它们添加到类中的顺序很重要。

举个例子

dart
class Bird extends Animal with Consumer, Flyer {

当在 Bird 的实例上调用方法时,Dart 从堆栈底部开始,从其自身的类 Bird 开始,它优先于其他实现。如果 Bird 没有实现,那么 Dart 会继续向上移动堆栈,接下来是 Flyer,然后是 Consumer,直到找到实现。如果找不到实现,则最后检查父类 Animal

扩展方法

#

与 Swift 一样,Dart 提供扩展方法,允许你向现有类型添加功能——特别是方法、getter、setter 和运算符。Dart 和 Swift 中创建扩展的语法看起来非常相似

dart
extension <name> on <type> {
  (<member definition>)*
}
swift
extension <type> {
  (<member definition>)*
}

例如,来自 Dart SDK 的 String 类的以下扩展允许解析整数

dart
extension NumberParsing on String {
  int parseInt() {
    return int.parse(this);
  }
}

print('21'.parseInt() * 2); // 42
swift
extension String {
  func parseInt() -> Int {
    return Int(self) ?? 0
  }
}

print("21".parseInt() * 2) // 42

虽然 Dart 和 Swift 中的扩展很相似,但仍有一些关键的区别。以下部分涵盖了最重要的区别,但请查看扩展方法以获得完整的概述。

命名扩展

#

虽然不是强制性的,但你可以在 Dart 中命名扩展。命名扩展允许你控制其作用域——这意味着可以隐藏或显示扩展,以防它与另一个库冲突。如果名称以下划线开头,则扩展仅在定义它的库中可用。

dart
// Hide "MyExtension" when importing types from
// "path/to/file.dart".
import 'path/to/file.dart' hide MyExtension; 
// Only show "MyExtension" when importing types
// from "path/to/file.dart".
import 'path/to/file.dart' show MyExtension;

// The `shout()` method is only available within this library.
extension _Private on String {
  String shout() => this.toUpperCase();
}

初始化器

#

在 Swift 中,你可以使用扩展向类型添加新的便利初始化器。在 Dart 中,你不能使用扩展向类添加额外的构造函数,但你可以添加一个静态扩展方法来创建类型的实例。考虑以下示例

dart
class Person {
  Person(this.fullName);

  final String fullName;
}

extension ExtendedPerson on Person {
  static Person create(String firstName, String lastName) {
    return Person("$firstName $lastName");
  }
}

// To use the factory method, use the name of
// the extension, not the type.
final person = ExtendedPerson.create('John', 'Doe');

重写成员

#

覆盖实例方法(包括运算符、getter 和 setter)在两种语言之间也非常相似。在 Dart 中,你可以使用 @override 注解来指示你正在有意覆盖成员

dart
class Animal {
  void makeNoise => print('Noise');
}

class Dog implements Animal {
  @override
  void makeNoise() => print('Woof woof');
}

在 Swift 中,你将 override 关键字添加到方法定义中

swift
class Animal {
  func makeNoise() {
    print("Noise")
  }
}

class Dog: Animal {
  override func makeNoise() {
    print("Woof woof"); 
  }
}

泛型

#

与 Swift 一样,Dart 支持使用泛型来提高类型安全性或减少代码重复。

泛型方法

#

你可以将泛型应用于方法。要定义泛型类型,请将其放在方法名称后的 < > 符号之间。然后可以在方法内(作为返回类型)或在方法的参数中使用此类型

dart
// Defining a method that uses generics.
T transform<T>(T param) {
  // For example,  doing some transformation on `param`...
  return param;
}

// Calling the method. Variable "str" will be
// of type String.
var str = transform('string value');

在这种情况下,将 String 传递给 transform 方法可确保它返回 String。同样,如果提供了 int,则返回值是 int

通过用逗号分隔来定义多个泛型

dart
// Defining a method with multiple generics.
T transform<T, Q>(T param1, Q param2) {
  // ...
}
// Calling the method with explicitly-defined types.
transform<int, String>(5, 'string value');
// Types are optional when they can be inferred.
transform(5, 'string value');

泛型类

#

泛型也可以应用于类。你可以在调用构造函数时指定类型,这允许你为特定类型定制可重用类。

在以下示例中,Cache 类用于缓存特定类型

dart
class Cache<T> {
  T getByKey(String key) {}
  void setByKey(String key, T value) {}
}
// Creating a cache for strings.
// stringCache has type Cache<String>
var stringCache = Cache<String>();
// Valid, setting a string value.
stringCache.setByKey('Foo', 'Bar')
// Invalid, int type doesn't match generic.
stringCache.setByKey('Baz', 5)

如果省略类型声明,则运行时类型为 Cache<dynamic>,并且对 setByKey 的两次调用都有效。

限制泛型

#

你可以使用泛型通过 extends 将你的代码限制为类型族。这确保你的类使用扩展特定类型的泛型类型实例化(并且与 Swift 类似)

dart
class NumberManager<T extends num> {
  // ...
}
// Valid
var manager = NumberManager<int>(); 
var manager = NumberManager<double>(); 
// Invalid, neither String nor its parent classes extend num.
var manager = NumberManager<String>();

字面量中的泛型

#

Map-Set-List- 字面量可以显式声明泛型类型,当类型未推断或推断不正确时,这很有用。

例如,List 类具有泛型定义:class List<E>。泛型类型 E 指的是列表内容的类型。通常,此类型会自动推断,这在 List 类的某些成员类型中使用。(例如,它的第一个 getter 返回 E 类型的值)。当定义 List 字面量时,你可以按如下方式显式定义泛型类型

dart
var objList = [5, 2.0]; // Type: List<num> // Automatic type inference
var objList = <Object>[5, 2.0]; // Type: List<Object> // Explicit type definition
var objSet = <Object>{5, 2.0}; // Sets work identically

Map 也是如此,它也使用泛型定义其 keyvalue 类型 (class Map<K, V>)

dart
// Automatic type inference
var map = {
  'foo': 'bar'
}; // Type: Map<String, String>
// Explicit type definition:
var map = <String, Object>{
  'foo': 'bar'
}; // Type: Map<String, Object>

并发

#

Swift 支持多线程,Dart 支持 isolates,它们类似于轻量级线程,这里不再赘述。每个 isolate 都有自己的事件循环。有关更多信息,请参阅Isolates 的工作原理

Future

#

原生 Swift 没有与 Dart 的 Future 对应的对象。但是,如果你熟悉 Apple 的 Combine 框架或 RxSwift 或 PromiseKit 等第三方库,你可能仍然知道这个对象。

简而言之,future 表示异步操作的结果,该结果将在稍后可用。如果你的函数返回 Future<String> 而不是仅仅返回 String,则你基本上是在接收一个可能在稍后——在未来——存在的值。

当 future 的异步操作完成时,该值变为可用。但是,你应该记住,future 也可能完成并出现错误,而不是一个值。

例如,如果你发出了 HTTP 请求,并立即收到一个 future 作为响应。一旦结果传入,future 就会完成并包含该值。但是,如果 HTTP 请求失败,例如由于互联网连接中断,future 将完成并出现错误。

Future 也可以手动创建。创建 future 的最简单方法是定义和调用 async 函数,这将在下一节中讨论。当你有需要成为 Future 的值时,你可以使用 Future 类轻松地将其转换为 future

dart
String str = 'String Value';
Future<String> strFuture = Future<String>.value(str);

Async/await

#

虽然 future 不是原生 Swift 的一部分,但 Dart 中的 async/await 语法在 Swift 中有对应的语法,并且工作方式类似,尽管没有 Future 对象。

与 Swift 中一样,函数可以标记为 async。Dart 中的区别在于,任何 async 函数总是隐式返回 Future。例如,如果你的函数返回 String,则此函数的 async 对应函数返回 Future<String>

Swift 中放置在 async 关键字之后的 throws 关键字(仅当函数是可抛出的时才放置)在 Dart 的语法中不存在,因为 Dart 异常和错误不会被编译器检查。相反,如果 async 函数中发生异常,则返回的 Future 会因异常而失败,然后可以适当地处理该异常。

dart
// Returns a future of a string, as the method is async
Future<String> fetchString() async {
  // Typically some other async operations would be done here.
  
  Response response = await makeNetworkRequest();
  if (!response.success) {
    throw BadNetwork();
  }

  return 'String Value';
}

然后可以按如下方式调用此 async 函数

dart
String stringFuture = await fetchString();
print(str); // "String Value"

Swift 中等效的 async 函数

swift
func fetchString() async throws -> String {
  // Typically some other async operations would be done here.
  let response = makeNetworkRequest()
  if !response.success {
    throw BadNetwork()
  }
  
  return "String Value"
}

同样,在 async 函数中发生的任何异常都可以使用 catchError 方法以与处理失败的 Future 相同的方式处理。

在 Swift 中,不能从非 async 上下文调用 async 函数。在 Dart 中,你被允许这样做,但你必须正确处理结果 Future。不必要地从非 async 上下文调用 async 函数被认为是糟糕的做法。

与 Swift 类似,Dart 也有 await 关键字。在 Swift 中,await 仅在调用 async 函数时可用,但 Dart 的 awaitFuture 类一起使用。因此,await 也适用于 async 函数,因为所有 async 函数都在 Dart 中返回 future。

等待 future 会暂停当前函数的执行并将控制权返回给事件循环,事件循环可以处理其他事情,直到 future 完成并返回一个值或一个错误。在此之后,await 表达式会评估为该值或抛出该错误。

当 future 完成时,将返回 future 的值。你只能在 async 上下文中 await,就像在 Swift 中一样。

dart
// We can only await futures within an async context.
asyncFunction() async {
  String returnedString = await fetchString();
  print(returnedString); // 'String Value'
}

当等待的 future 失败时,会在带有 await 关键字的行上抛出一个错误对象。你可以使用常规的 try-catch 块来处理此问题

dart
// We can only await futures within an async context.
Future<void> asyncFunction() async {
  String? returnedString;
  try {
    returnedString = await fetchString();
  } catch (error) {
    print('Future encountered an error before resolving.');
    return;
  }
  print(returnedString);
}

有关更多信息和互动练习,请查看异步编程教程。

Stream

#

Dart 异步工具箱中的另一个工具是 Stream 类。虽然 Swift 有自己的 stream 概念,但 Dart 中的 stream 类似于 Swift 中的 AsyncSequence。同样,如果你了解 Observables(在 RxSwift 中)或 Publishers(在 Apple 的 Combine 框架中),Dart 的 stream 应该会让你感到熟悉。

对于那些不熟悉 StreamsAsyncSequencePublishersObservables 的人来说,概念如下:Stream 本质上就像 Future,但具有多个值,这些值会随着时间的推移分散开来,就像一个事件总线。可以监听 stream 以接收值或错误事件,并且当不再发送任何事件时,可以关闭 stream。

监听

#

要监听 stream,你可以将 stream 与 async 上下文中的 for-in 循环结合使用。for 循环为发出的每个项目调用回调方法,并在 stream 完成或出错时结束

dart
Future<int> sumStream(Stream<int> stream) async {
  var sum = 0;
  try { 
    await for (final value in stream) {
      sum += value;
    }
  } catch (error) {
    print('Stream encountered an error! $err');
  }
  return sum;
}

如果在监听 stream 时发生错误,则会在包含 await 关键字的行上抛出错误,你可以使用 try-catch 语句处理该错误

dart
try {
  await for (final value in stream) { ... }
} catch (err) {
  print('Stream encountered an error! $err');
}

这不是监听 stream 的唯一方法:你还可以调用其 listen 方法并提供回调,每当 stream 发出值时都会调用回调

dart
Stream<int> stream = ...
stream.listen((int value) {
  print('A value has been emitted: $value');
});

listen 方法有一些可选的回调,用于错误处理或 stream 完成时

dart
stream.listen(
  (int value) { ... },
  onError: (err) {
    print('Stream encountered an error! $err');
  },
  onDone: () {
    print('Stream completed!');
  },
);

listen 方法返回 StreamSubscription 的实例,你可以使用它来停止监听 stream

dart
StreamSubscription subscription = stream.listen(...);
subscription.cancel();

创建 Stream

#

与 future 一样,你有几种不同的方法来创建 stream。两种最常见的方法是使用异步生成器或 SteamController

异步生成器
#

异步生成器函数的语法与同步生成器函数相同,但使用 async* 关键字而不是 sync*,并返回 Stream 而不是 Iterable。这种方法类似于 Swift 中的 AsyncStream 结构。

在异步生成器函数中,yield 关键字将给定的值发出到 stream。但是,yield* 关键字与 stream 而不是其他 iterable 一起使用。这允许将来自其他 stream 的事件发出到此 stream。在以下示例中,函数仅在新产生的 stream 完成后才继续

dart
Stream<int> asynchronousNaturalsTo(int n) async* {
  int k = 0;
  while (k < n) yield k++;
}

Stream<int> stream = asynchronousNaturalsTo(5);

你还可以使用 StreamController API 创建 stream。有关更多信息,请参阅使用 StreamController

文档注释

#

常规注释在 Dart 中的工作方式与在 Swift 中的工作方式相同。使用双反斜杠 (//) 注释掉双反斜杠之后到行尾的所有内容,/* ... */ 代码块注释跨越多行。

除了常规注释外,Dart 还有文档注释,它与dart doc协同工作:这是一个第一方工具,用于为 Dart 包生成 HTML 文档。最佳实践是在所有公共成员的声明之上放置文档注释。你可能会注意到,此过程类似于你在 Swift 中为各种文档生成工具添加注释的方式。

与 Swift 中一样,你可以通过使用三个正斜杠而不是两个 (///) 来定义文档注释

dart
/// The number of characters in this chunk when unsplit.
int get length => ...

在文档注释中,用方括号括起来类型、参数和方法名称。

dart
/// Returns the [int] multiplication result of [a] * [b].
multiply(int a, int b) => a * b;

虽然支持 JavaDoc 样式的文档注释,但你应该避免使用它们并使用 /// 语法。

dart
/** 
 * The number of characters in this chunk when unsplit. 
 * (AVOID USING THIS SYNTAX, USE /// INSTEAD.)
 */
int get length => ...

库和可见性

#

Dart 的可见性语义与 Swift 的相似,Dart 库大致相当于 Swift 模块。

Dart 提供两个级别的访问控制:公共和私有。方法和变量默认是公共的。私有变量以强调字符 (_) 为前缀,并由 Dart 编译器强制执行。

dart
final foo = 'this is a public property';
final _foo = 'this is a private property';

String bar() {
  return 'this is a public method';
}
String _bar() {
  return 'this is a private method';
}

// Public class
class Foo {
}

// Private class
class _Foo {
},

私有方法和变量的作用域在 Dart 中限定于其库,在 Swift 中限定于模块。在 Dart 中,你可以在一个文件中定义一个库,而在 Swift 中,你必须为你的模块创建一个新的构建目标。这意味着在一个 Dart 项目中,你可以定义 n 个库,但在 Swift 中,你必须创建 n 个模块。

作为库一部分的所有文件都可以访问该库中的所有私有对象。但出于安全原因,文件仍然需要允许特定文件访问其私有对象,否则任何文件(甚至来自项目外部的文件)都可以将其自身注册到你的库并访问可能敏感的数据。换句话说,私有对象不会跨库共享。

animal.dart
dart
library animals;

part 'parrot.dart';

class _Animal {
  final String _name;

  _Animal(this._name);
}
parrot.dart
dart
part of animals;

class Parrot extends _Animal {
  Parrot(String name) : super(name);

  // Has access to _name of _Animal
  String introduction() {
    return 'Hello my name is $_name';
  }
}

有关更多信息,请查看创建包

下一步

#

本指南向你介绍了 Dart 和 Swift 之间的主要区别。此时,你可以考虑转到DartFlutter(一个开源框架,它使用 Dart 来构建美观、原生编译的多平台应用程序,只需一个代码库)的通用文档,在那里你将找到有关该语言的深入信息以及入门的实用方法。