跳到主要內容

身為 Swift 開發者學習 Dart

本指南旨在您學習 Dart 時,能運用您的 Swift 程式設計知識。它展示了兩種語言的主要相似之處和差異,並介紹了 Swift 中不存在的 Dart 概念。身為 Swift 開發者,Dart 可能會讓您感到熟悉,因為這兩種語言都共享許多概念。

Swift 和 Dart 都支援健全的 Null 安全性。兩種語言預設都不允許變數為 null。

與 Swift 類似,Dart 也對集合泛型並行(使用 async/await)和擴展提供類似的支援。

Mixins 是 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 中,當沒有明確類型的變數在其宣告後初始化時,其類型會推斷為 catch-all 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 在平台函式庫中包含許多類型,例如

  • 基本值類型,例如
    • 數字 (numintdouble)
    • 字串 (String)
    • 布林值 (bool)
    • 值 null (Null)
  • 集合
    • 清單/陣列 (List)
    • Sets (Set)
    • Maps/字典 (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 語言導覽中的Runes 和字形叢集

字串串連和多行宣告

#

在 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 中定義原始字串。原始字串會忽略逸出字元,並包含字串中存在的任何特殊字元。您可以在 Dart 中透過在字串常值前加上字母 r 來執行此操作,如下列範例所示。

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) 中都代表二進位值。

Null 安全性

#

Dart 強制執行健全的 Null 安全性。預設情況下,類型不允許 null 值,除非標記為可為 null。Dart 使用問號 (?) 在類型末尾表示這一點。這就像 Swift 的可選值

Null 感知運算子

#

Dart 支援多個運算子來處理可為 null 性。Null 合併運算子 (??) 和可選鏈結運算子 (?.) 在 Dart 中可用,並且運作方式與 Swift 中相同。

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

此外,Dart 還提供串聯運算子的 Null 安全版本 (?..)。當目標表達式解析為 null 時,此運算子會忽略任何運算。Dart 也提供 Null 指派運算子 (??=),Swift 沒有。如果可為 null 類型的變數的目前值為 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

! 運算子(也稱為「強制解包」)

#

在可以安全地假設可為 null 的變數或表達式實際上是非 null 的情況下,可以告訴編譯器抑制任何編譯時期錯誤。這是透過使用後綴 ! 運算子來完成的,方法是將其作為表達式的後綴放置。(不要將其與 Dart 的「not」運算子混淆,後者使用相同的符號。)

dart
int? a = 5;

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

在執行階段,如果 a 結果為 null,則會發生執行階段錯誤。

?. 運算子類似,在存取物件上的屬性或方法時使用 ! 運算子。

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

如果 myObject 在執行階段為 null,則會發生執行階段錯誤。

Late 欄位

#

late 關鍵字可以指派給類別欄位,以指示它們在稍後的時間點初始化,同時保持非可為 null。這與 Swift 的「隱式解包的可選值」類似。這對於在初始化之前永遠不會觀察到變數的情況很有用,允許稍後初始化它。非可為 null 的 late 欄位稍後無法指派 null。此外,非可為 null 的 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 上有多個 tuple 套件可用)。如果函式需要傳回多個值,您可以將它們包裝在集合中,例如清單、set 或 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
}

具名參數必須包含以下其中之一。

  • 預設值
  • 類型末尾的 ?,將類型設定為可為 null
  • 變數類型之前的關鍵字 required

若要深入了解可為 null 的類型,請查看Null 安全性

若要在 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
}

與具名參數類似,可選位置參數必須具有預設值或可為 null 的類型。

First-class 函式

#

與 Swift 中一樣,Dart 函式也是 first class citizens,這表示它們被視為任何其他物件。例如,以下程式碼顯示如何從函式傳回函式。

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].

這是同步產生器函式的範例。您也可以定義非同步產生器函式,這些函式傳回 streams 而不是 iterables。在並行章節中了解更多資訊。

陳述式

#

本節介紹 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 沒有任何特殊的 for-in 迴圈語法,允許您迴圈遍歷 map,就像 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 陳述式範圍內本機變數的類型。這也適用於 Null 檢查。提升僅適用於本機變數,而不適用於實例變數。

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 中對應項的比較。

Lists

#

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 中的另一個實用功能是展開運算子 (...) 和可為 null 感知的展開運算子 (...?),它們提供了一種簡潔的方式將多個值插入集合中。

例如,您可以使用展開運算子 (...) 將清單的所有值插入另一個清單中,如下所示。

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,您可以使用可為 null 感知的展開運算子 (...?) 來避免例外。

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

Sets

#

Dart 和 Swift 都支援使用字面值定義 Set。Set 的定義方式與 List 相同,但使用大括號而非方括號。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"]

Maps

#

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 關鍵字。

列舉

#

列舉型別,通常稱為列舉 (enumerations) 或 enums,是一種特殊的類別,用於表示固定數量的常數值。Enums 長期以來一直是 Dart 語言的一部分,但 Dart 2.17 新增了對成員的增強型 enums 支援。這表示您可以新增包含狀態的欄位、設定該狀態的建構子、具有功能的方法,甚至覆寫現有的成員。如需更多資訊,請查看 Dart 語言導覽中的宣告增強型 enums

建構子

#

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)');
  }
  ...
}

初始化器列表是使用 assert 的好地方。

具名建構子

#

與 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);
}

Factory 建構子

#

當您不需要建立新的類別實例時,可以使用 factory 建構子。一個範例是,如果可以改為傳回快取的實例

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..
  }
}

Getters 和 setters

#

您可以透過在欄位名稱前加上 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...
}

Mixins

#

Mixins 允許您的程式碼在類別之間共用功能。您可以在類別中使用 mixin 的欄位和方法,就好像它們是類別的一部分一樣使用它們的功能。一個類別可以使用多個 mixins——這在多個類別共用相同功能時非常有用——而無需彼此繼承或共用共同的祖先。

雖然 Swift 不支援 mixins,但如果您編寫一個協定以及一個為協定中指定的方法提供預設實作的擴充,則可以近似此功能。此方法的主要問題是,與 Dart 不同,這些協定擴充不會維護自己的狀態。

您可以像宣告一般類別一樣宣告 mixin,只要它不擴充 Object 以外的任何類別,並且沒有建構子。使用 with 關鍵字將一個或多個逗號分隔的 mixins 新增到類別中。

以下範例顯示如何在 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 可防止 mixin 被用作一般類別。

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

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

由於您可以使用多個 mixins,因此它們的方法或欄位在同一個類別上使用時可能會彼此重疊。它們甚至可能與使用它們的類別或該類別的超類別重疊。為了解決這個問題,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>();

Literals 中的泛型

#

Map-Set-List- 字面值可以明確宣告泛型型別,這在型別未推斷或推斷不正確時非常有用。

例如,List 類別具有泛型定義:class List<E>。泛型型別 E 是指 list 內容的型別。通常,此型別會自動推斷,這會在 List 類別的某些成員型別中使用。(例如,其 first 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 也是如此,它也使用泛型 (class Map<K, V>) 定義其 keyvalue 型別

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 的運作方式

Futures

#

Vanilla Swift 沒有與 Dart 的 Future 相對應的東西。但是,如果您熟悉 Apple 的 Combine 框架,或 RxSwift 或 PromiseKit 等第三方程式庫,您可能仍然認識這個物件。

簡而言之,future 代表非同步操作的結果,該結果會在稍後的時間變得可用。如果您有一個函式傳回 Future<String> 而不是僅僅傳回 String,則您基本上會收到一個可能在稍後某個時間點存在的值——在未來。

當 future 的非同步操作完成時,該值將變得可用。但是,您應該記住,future 也可能在完成時發生錯誤,而不是值。

一個範例是您發出 HTTP 請求,並立即收到 future 作為回應。一旦結果傳入,future 就會完成並帶有該值。但是,如果 HTTP 請求失敗,例如因為網路連線中斷,future 會在完成時發生錯誤。

Futures 也可以手動建立。建立 future 最簡單的方法是定義和呼叫 async 函式,這將在下一節中討論。當您有一個需要是 Future 的值時,您可以使用 Future 類別輕鬆地將其轉換為 future

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

Async/await

#

雖然 futures 不是 vanilla 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 的 await 可與 Future 類別一起使用。因此,await 也適用於 async 函式,因為所有 async 函式在 Dart 中都會傳回 futures。

等待 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);
}

如需更多資訊和互動式練習,請查看非同步程式設計教學課程。

Streams

#

Dart 非同步工具箱中的另一個工具是 Stream 類別。雖然 Swift 有自己的 streams 概念,但 Dart 中的 streams 類似於 Swift 中的 AsyncSequence。同樣地,如果您知道 Observables(在 RxSwift 中)或 Publishers(在 Apple 的 Combine 框架中),Dart 的 streams 應該會感到熟悉。

對於那些不熟悉 StreamsAsyncSequencePublishersObservables 的人來說,概念如下:Stream 本質上就像 Future 一樣運作,但具有多個隨時間推移散佈的值,就像事件匯流排。可以監聽 streams 以接收值或錯誤事件,並且當不再發送其他事件時,可以關閉它們。

監聽

#

若要監聽 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();

建立 Streams

#

與 futures 一樣,您有多種不同的方式來建立 stream。兩種最常見的方式是使用 async generator 或 SteamController

Async generators
#

Async generator 函式的語法與同步 generator 函式相同,但使用 async* 關鍵字而不是 sync*,並傳回 Stream 而不是 Iterable。此方法類似於 Swift 中的 AsyncStream struct。

在 async generator 函式中,yield 關鍵字會將給定的值發送到 stream。但是,yield* 關鍵字適用於 streams 而不是其他 iterables。這允許將來自其他 streams 的事件發送到此 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

Doc 註解

#

常規註解在 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 提供兩個層級的存取控制:public 和 private。方法和變數預設為 public。Private 變數以底線字元 (_) 作為前綴,並由 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 {
},

Private 方法和變數在 Dart 中限定於其程式庫,而在 Swift 中則限定於模組。在 Dart 中,您可以在檔案中定義程式庫,而在 Swift 中,您必須為您的模組建立新的建置目標。這表示在單個 Dart 專案中,您可以定義 n 個程式庫,但在 Swift 中,您必須建立 n 個模組。

屬於程式庫的所有檔案都可以存取該程式庫中的所有 private 物件。但是,出於安全考量,檔案仍然需要允許特定檔案存取其 private 物件,否則任何檔案(甚至來自專案外部的檔案)都可以在您的程式庫中註冊自身並存取可能敏感的資料。換句話說,private 物件不會在程式庫之間共用。

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 的一般文件(Flutter 是一個開源框架,它使用 Dart 從單個程式碼庫建置美觀、原生編譯、多平台應用程式),您可以在其中找到有關語言的深入資訊以及開始使用的實用方法。