Swift 開發人員學習 Dart
本指南旨在利用您在學習 Dart 時的 Swift 程式設計知識。它展示了兩種語言中的主要相似性和差異,並介紹了 Swift 中不存在的 Dart 概念。對於 Swift 開發人員而言,Dart 可能會感到熟悉,因為這兩種語言共享許多概念。
Swift 和 Dart 都支援健全的 Null 安全性。這兩種語言都不允許變數預設為 Null。
與 Swift 類似,Dart 對 集合、泛型、並行處理(使用 async/await)和 擴充方法 有類似的支援。
混入 是 Dart 中的另一個概念,對於 Swift 開發人員來說可能是新的。與 Swift 類似,Dart 提供 AOT(即時編譯)。但是,Dart 也支援 JIT(即時編譯)編譯模式,以協助各種開發層面,例如增量重新編譯或除錯。如需更多資訊,請查看 Dart 概觀。
慣例和 linting
#Swift 和 Dart 都具有強制執行標準慣例的程式碼檢查工具。但是,Swift 將 SwiftLint 作為一個獨立的工具,而 Dart 則有官方版面配置慣例,並包含一個程式碼檢查器,讓您能輕鬆地遵循慣例。若要自訂專案的程式碼檢查規則,請遵循 自訂靜態分析 說明。(請注意,Dart 和 Flutter 的 IDE 外掛也提供此功能。)
Dart 也提供一個程式碼格式化器,它可以在從命令列執行 dart format 或透過 IDE 時自動格式化任何 Dart 專案。
有關 Dart 約定和 linting 的更多資訊,請查看 Effective Dart 和 Linter rules。
變數
#與 Swift 相比,在 Dart 中宣告和初始化變數稍有不同。變數宣告總是從變數的型別、var 關鍵字或 final 關鍵字開始。與 Swift 一樣,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。
// 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 等效程式碼如下所示
// 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 linter 會透過產生警告來阻止這種情況。如果您打算讓變數具有任何型別,建議將其指派給 Object? 而不是 dynamic。
有關更多資訊,請查看 Dart 語言導覽中的 變數區段。
final
#Dart 中的 final 關鍵字表示只能設定變數一次。這類似於 Swift 中的 let 關鍵字。
在 Dart 和 Swift 中,您只能初始化 final 變數一次,無論是在宣告陳述式中或是在初始化器清單中。任何嘗試第二次指派值的行為都會導致編譯時期錯誤。以下兩個程式碼片段都是有效的,但隨後設定 name 會導致編譯錯誤。
final String name;
if (b1) {
name = 'John';
} else {
name = 'Jane';
}let name: String
if (b1) {
name = "John"
} else {
name = "Jane"
}const
#除了 final 之外,Dart 也有 const 關鍵字。const 的一個好處是它在編譯時期會被完全評估,且在應用程式的生命週期中無法修改。
const bar = 1000000; // Unit of pressure (dynes/cm2)
const double atm = 1.01325 * bar; // Standard atmosphere在類別層級定義的 const 變數需要標記為 static const。
class StandardAtmosphere {
static const bar = 1000000; // Unit of pressure (dynes/cm2)
static const double atm = 1.01325 * bar; // Standard atmosphere
}const 關鍵字不只用於宣告常數變數;它也可以用於建立常數值
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 欄位,但可以使用常數。例如
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 (
Null)
- 數字 (
- 集合
- 清單/陣列 (
List) - 集合 (
Set) - 對應/字典 (
Map)
- 清單/陣列 (
如需更多資訊,請查看 Dart 語言導覽中的 內建類型。
數字
#Dart 定義了三種數字類型來儲存數字
num- 一般 64 位元數字類型。
int- 與平台相關的整數數字。在原生程式碼中,它是一個 64 位元二補數整數。在網頁上,它是一個非分數 64 位元浮點數。
double- 一個 64 位元浮點數。
與 Swift 不同,沒有特定類型用於無符號整數。
所有這些類型在 Dart API 中也是類別。int 和 double 類型都將 num 共用為它們的父類別
由於數字值在技術上是類別執行個體,因此它們很方便地公開自己的公用程式函式。因此,int 可以轉換成 double,如下所示
int intVariable = 3;
double doubleVariable = intVariable.toDouble();在 Swift 中使用特殊初始化程式可以達成相同的效果
var intVariable: Int = 3
var doubleVariable: Double = Double(intVariable)在字面值的情況下,Dart 會自動將整數字面值轉換成 double 值。以下程式碼完全正確
double doubleValue = 3;與 Swift 不同,在 Dart 中,您可以使用等於 (==) 算子將整數值與雙精度值進行比較,如下所示
int intVariable = 3;
double doubleVariable = 3.0;
print(intVariable == doubleVariable); // true這段程式碼會印出 true。不過,在 Dart 中,底層實作數字在網頁和原生平台之間有所不同。Dart 中的數字 頁面詳細說明這些差異,並說明如何撰寫程式碼,讓這些差異無關緊要。
字串
#與 Swift 一樣,Dart 使用 String 類型表示一系列字元,但 Dart 不支援代表一個字元的 Character 類型。String 可以用單引號或雙引號定義,不過,建議使用單引號。
String c = 'a'; // There isn't a specialized "Character" type
String s1 = 'This is a String';
String s2 = "This is also a String";let c: Character = "a"
let s1: String = "This is a String"
let s2: String = "This is also a String"跳脫特殊字元
#在 Dart 中跳脫特殊字元與 Swift(以及大多數其他語言)類似。若要包含特殊字元,請使用反斜線字元跳脫它們。
以下程式碼顯示一些範例
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 有多種方法可以定義多行字串
使用隱式字串串接:任何相鄰的字串文字都會自動串接,即使分佈在多行中
dartfinal s1 = 'String ' 'concatenation' " even works over line breaks.";使用多行字串文字:在字串兩側使用三個引號(單引號或雙引號)時,允許文字跨越多行
dartfinal s2 = '''You can create multiline strings like this one.'''; final s3 = """This is also a multiline string.""";Dart 也支援使用
+算子串接字串。這適用於字串文字和字串變數dartfinal name = 'John'; final greeting = 'Hello ' + name + '!';
字串內插
#使用 ${<expression>} 語法將運算式插入字串文字中。Dart 透過允許在運算式為單一識別碼時省略大括號來擴充此功能
var food = 'bread';
var str = 'I eat $food'; // I eat bread
var str = 'I eat ${bakery.bestSeller}'; // I eat bread在 Swift 中,您可以透過將變數或運算式括在括號中並加上反斜線前置詞來達成相同的結果
let s = "string interpolation"
let c = "Swift has \(s), which is very handy."原始字串
#與 Swift 一樣,您可以在 Dart 中定義原始字串。原始字串會忽略跳脫字元,並包含字串中存在的任何特殊字元。您可以在 Dart 中透過在字串文字前加上字母 r 來執行此操作,如下面的範例所示。
// 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.
""";let s1 = #"Includes the \n characters."#
let s2 = #"""
The \n characters are also included
when using raw multiline strings.
"""#相等性
#與 Swift 一樣,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 檢查字串是否為空。還有其他便利方法,例如 toUpperCase 和 toLowerCase。有關詳細資訊,請查看 Dart 語言導覽中的字串。
布林值
#布林值在 Dart (bool) 和 Swift (Bool) 中都表示二進位值。
Null 安全性
#Dart 強制執行健全的 Null 安全性。預設情況下,除非標記為可為 Null,否則類型不允許 Null 值。Dart 會在類型結尾加上問號 (?) 來表示這一點。這與 Swift 的選項類似。
Null 感知運算子
#Dart 支援多個處理 Null 值的算子。Dart 中提供了 Null 合併運算子 (??) 和可選鏈接運算子 (?.),其運作方式與 Swift 中相同
a = a ?? b;let str: String? = nil
let count = str?.count ?? 0此外,Dart 提供了串接運算子 (?..) 的 null 安全版本。當目標表達式解析為 null 時,此運算子會忽略任何運算。Dart 也提供了 Swift 沒有的 null 指定運算子 (??=)。如果具有可為 null 類型的變數目前的值為 null,此運算子會將值指定給該變數。表示為 a ??= b;,它作為下列內容的簡寫
a = a ?? b;
// Assign b to a if a is null; otherwise, a stays the same
a ??= b;a = a ?? b!運算子(也稱為「強制解開」)
#在可以安全假設可為 null 的變數或表達式實際上為非 null 的情況下,可以指示編譯器抑制任何編譯時期錯誤。這是透過將後綴 ! 運算子作為後綴加到表達式來完成的。(不要將此與 Dart 的「非」運算子混淆,它使用相同的符號)
int? a = 5;
int b = a; // Not allowed.
int b = a!; // Allowed.在執行時期,如果 a 變成 null,就會發生執行時期錯誤。
與 ?. 運算子一樣,在存取物件上的屬性或方法時使用 ! 運算子
myObject!.someProperty;
myObject!.someMethod();如果 myObject 在執行時期為 null,就會發生執行時期錯誤。
延遲欄位
#late 關鍵字可以指定給類別欄位,以表示它們會在稍後初始化,同時保持為非 null。這類似於 Swift 的「隱含解開選項」。這對於在初始化之前從未觀察過變數的情況很有用,允許稍後初始化它。非 null 的 late 欄位不能在稍後指定為 null。此外,非 null 的 late 欄位在初始化之前觀察到時會擲回執行時期錯誤,這是您要在表現良好的應用程式中避免的場景。
// 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 關鍵字與初始化程式結合使用,以使初始化變為延遲
class Weather {
late int _temperature = _readThermometer();
}在這種情況下,_readThermometer() 僅在第一次存取欄位時執行,而不是在初始化時執行。
Dart 的另一個優點是使用 late 關鍵字來延遲 final 變數的初始化。雖然在將 final 變數標記為 late 時不必立即初始化它,但它仍然只能初始化一次。第二次指定會導致執行時期錯誤。
late final int a;
a = 1;
a = 2; // Throws a runtime exception because
// "a" is already initialized.函式
#Swift 使用 main.swift 檔案作為應用程式的進入點。Dart 使用 main 函式作為應用程式的進入點。每個程式都必須有一個 main 函式才能執行。例如
void main() {
// main function is the entry point
print("hello world");
}// main.swift file is the entry point
print("hello world")Dart 不支援 Tuples(儘管 pub.dev 上有 幾個 tuple 套件)。如果函式需要傳回多個值,您可以將它們包裝在集合中,例如清單、集合或映射,或者您可以撰寫包裝類別,其中可以傳回包含這些值的執行個體。可以在 集合 和 類別 部分中找到更多相關資訊。
例外和錯誤處理
#與 Swift 相同,Dart 的函式和方法支援處理 例外狀況 和 錯誤。Dart 的錯誤通常表示程式設計師的錯誤或系統故障,例如堆疊溢位。Dart 錯誤不應該被捕捉。另一方面,Dart 的例外狀況表示可復原的故障,且預期會被捕捉。例如,在執行階段,程式碼可能會嘗試存取串流資料,但卻收到例外狀況,如果未捕捉,就會導致應用程式終止。您可以透過將函式呼叫包覆在 try-catch 區塊中,來管理 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 區塊。例如
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 區塊。如需更多資訊,請參閱 Error 和 Exception 類別的說明文件。
參數
#與 Swift 類似,Dart 在其函式中支援命名參數。然而,與 Swift 不同的是,這些參數在 Dart 中並非預設。Dart 中的預設參數類型是位置參數。
int multiply(int a, int b) {
return a * b;
}Swift 中的等效方式是在參數前加上底線,以移除對引數標籤的需求。
func multiply(_ a: Int, _ b: Int) -> Int {
return a * b
}在 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// The Swift equivalent
func multiply(_ a: Int, _ b: Int, c: Int = 1, d: Int = 1) -> Int {
return a * b * c * d
}命名參數必須包含下列其中一項
- 預設值
- 類型結尾的
?,將類型設定為可為空 - 變數類型前的關鍵字
required
如需深入瞭解可為空類型,請查看 空值安全性。
若要在 Dart 中將命名參數標記為必要,您必須在參數前加上 required 關鍵字
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);第三種參數類型是選擇性位置參數。顧名思義,這些參數類似於預設位置參數,但呼叫函式時可以省略這些參數。這些參數必須列在任何必要的位置參數之後,且不能與命名參數一起使用。
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// The Swift equivalent
func multiply(_ a: Int, _ b: Int, _ c: Int = 1, _ d: Int = 1) -> Int {
return a * b * c * d
}與命名參數一樣,選擇性位置參數必須具有預設值或可為空類型。
一級函式
#與 Swift 一樣,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// 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 有兩種宣告匿名函式的方法。第一種方法使用大括號,其運作方式與任何其他函式相同。它允許您使用多行,而且需要回傳陳述式才能傳回任何值。
// Multi line anonymous function
[1,2,3].map((element) {
return element * 2;
}).toList(); // [2, 4, 6] // Swift equivalent anonymous function
[1, 2, 3].map { $0 * 2 }另一種方法使用箭頭函式,其名稱源自其語法中使用的箭頭狀符號。當您的函式主體只包含一個表示式,且會傳回值時,您可以使用這種簡寫語法。這會省略使用大括號或回傳陳述式的需要,因為它們是暗示的。
// Single-line anonymous function
[1,2,3].map((element) => element * 2).toList(); // [2, 4, 6]箭頭語法或大括號的選擇適用於任何函式,不只匿名函式。
multiply(int a, int b) => a * b;
multiply(int a, int b) {
return a * b;
}產生器函式
#Dart 支援 產生器函式,其傳回一個惰性建構的項目可迭代集合。使用 yield 關鍵字將項目新增到最終的可迭代集合,或使用 yield* 新增整個項目集合。
以下範例顯示如何撰寫基本產生器函式
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].這是同步產生器函式的範例。您也可以定義非同步產生器函式,其傳回串流而不是可迭代集合。在 並行處理 部分中深入了解。
陳述式
#本節涵蓋 Dart 和 Swift 之間陳述式的相似性和差異性。
控制流程(if/else、for、while、switch)
#Dart 中的所有控制流程陳述式運作方式都與其 Swift 對應項類似,只在語法上有些許差異。
if
#與 Swift 不同,Dart 中的 if 陳述式需要在條件周圍加上括號。雖然 Dart 風格指南建議在流程控制陳述式周圍使用大括號(如下所示),但當您有一個沒有 else 子句且整個 if 陳述式都放在一行上的 if 陳述式時,您可以省略大括號(如果您願意)。
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');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 迴圈,以及用於迴圈處理集合的 for-in。
Dart 的 for-in 迴圈與 Swift 的對應迴圈運作方式相同,它可以迴圈遍歷任何 Iterable 值,如下方的 List 範例
var list = [0, 1, 2, 3, 4];
for (var i in list) {
print(i);
}let array = [0, 1, 2, 3, 4]
for i in array {
print(i)
}Dart 的 for-in 迴圈沒有任何特殊語法,可以讓您迴圈遍歷地圖,就像 Swift 對字典所做的那樣。若要達成類似的效果,您可以將地圖的項目萃取為 Iterable 類型。或者,您可以使用 Map.forEach
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');
});var dict:[String:Int] = [
"Foo":1,
"Bar":2
]
for (key, value) in dict {
print("\(key),\(value)")
}運算子
#與 Swift 不同,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);
}
}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 等效項目的運作方式相同。例如
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 T | expr as! T expr as? T |
| 如果物件具有指定的類型,則為 True | expr is T | expr is T |
| 如果物件不具有指定的類型,則為 True | expr is! T | !(expr is T) |
如果 obj 是 T 指定的類型的子類型,則 obj is T 的結果為 true。例如,obj is Object? 永遠為 true。
使用類型轉換運算子將物件轉換為特定類型,前提是您確定物件屬於該類型。例如
(person as Employee).employeeNumber = 4204583;Dart 只有單一類型轉換運算子,其作用類似於 Swift 的 as! 運算子。Swift 的 as? 運算子沒有等效項目。
(person as! Employee).employeeNumber = 4204583;如果您不確定物件是否為 T 類型,請使用 is T 在使用物件之前進行檢查。
在 Dart 中,類型提升會更新 if 陳述式範圍內局部變數的類型。這也會發生在 null 檢查上。提升只適用於局部變數,不適用於實例變數。
if (person is Employee) {
person.employeeNumber = 4204583;
}// Swift requires the variable to be cast.
if let person = person as? Employee {
print(person.employeeNumber)
}邏輯運算子
#邏輯運算子 (例如 AND (&&)、OR (||) 和 NOT (!)) 在這兩種語言中都是相同的。例如
if (!done && (col == 0 || col == 3)) {
// ...Do something...
}位元運算子和位移運算子
#位元運算子在兩種語言中幾乎相同。
例如
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 陳述式的運算式
final displayLabel = canAfford ? 'Please pay below' : 'Insufficient funds';let displayLabel = canAfford ? "Please pay below" : "Insufficient funds"串接 (.. 運算子)
#與 Swift 不同,Dart 支援使用串接運算子進行串接。這讓您可以在單一物件上串連多個方法呼叫或屬性指定。
下列範例顯示如何設定多個屬性的值,然後在一個新建立的物件上呼叫多個方法,所有這些都在單一串接中使用串接運算子
Animal animal = Animal()
..name = 'Bob'
..age = 5
..feed()
..walk();
print(animal.name); // "Bob"
print(animal.age); // 5var animal = Animal()
animal.name = "Bob"
animal.age = 5
animal.feed()
animal.walk()
print(animal.name)
print(animal.age)集合
#本節涵蓋 Swift 中的一些集合類型,以及它們與 Dart 中的等效項之間的比較。
清單
#List 文字在 Dart 中的定義方式與 Swift 中的陣列相同,使用方括號並以逗號分隔。兩種語言之間的語法非常相似,但有一些細微的差異,如下列範例所示
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 typevar 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 運算子從清單中擷取值
final fruits = ['apple', 'orange', 'pear'];
final fruit = fruits[1];若要將值新增到清單的後面,請使用 add 方法。若要新增另一個 List,請使用 addAll 方法
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。
final fruits = List<String>.unmodifiable(['apple', 'orange', 'pear']);let fruits = ["apple", "orange", "pear"]散佈運算子
#Dart 中的另一個有用功能是散佈運算子 (...) 和空值感知散佈運算子 (...?),它們提供了將多個值插入集合的簡潔方式。
例如,您可以使用散佈運算子 (...) 將清單的所有值插入另一個清單,如下所示
final list = [1, 2, 3];
final list2 = [0, ...list]; // [ 0, 1, 2, 3 ]
assert(list2.length == 4);雖然 Swift 沒有散佈運算子,但等同於上述第 2 行的寫法如下
let list2 = [0] + list如果散佈運算子右邊的表達式可能是 null,您可以使用空值感知散佈運算子 (...?) 來避免例外狀況
List<int>? list;
final list2 = [0, ...?list]; //[ 0 ]
assert(list2.length == 1);let list2 = [0] + list ?? []集合
#Dart 和 Swift 都支援使用文字定義 Set。Set 的定義方式與清單相同,但使用花括號而不是方括號。Set 是無序集合,只包含唯一項目。這些項目的唯一性是使用雜湊碼實作的,這表示物件需要雜湊值才能儲存在 Set 中。每個 Dart 物件都包含一個雜湊碼,而在 Swift 中,您需要在物件可以儲存在 Set 中之前明確套用 Hashable 協定。
以下程式碼片段顯示了在 Dart 和 Swift 中初始化 Set 的差異
final abc = {'a', 'b', 'c'};var abc: Set<String> = ["a", "b", "c"]您無法在 Dart 中透過指定空的花括號 ({}) 來建立空的集合;這會建立一個空的 Map。若要建立空的 Set,請在 {} 宣告之前加上類型引數,或將 {} 指定給類型為 Set 的變數
final names = <String>{};
Set<String> alsoNames = {}; // This works, too.
// final names = {}; // Creates an empty map, not a set.不可修改
#類似於 List,Set 也有不可變版本。例如
final abc = Set<String>.unmodifiable(['a', 'b', 'c']);let abc: Set<String> = ["a", "b", "c"]對應
#Dart 中的 Map 類型可以與 Swift 中的 Dictionary 類型相比較。這兩種類型都關聯鍵和值。這些鍵和值可以是任何類型的物件。每個鍵只出現一次,但您可以多次使用相同的值。
在兩種語言中,字典都基於雜湊表,這表示鍵需要可雜湊。在 Dart 中,每個物件都包含雜湊,而在 Swift 中,您需要在物件可以儲存在 Dictionary 中之前明確套用 Hashable 協定。
以下是使用文字建立的幾個簡單 Map 和 Dictionary 範例
final gifts = {
'first': 'partridge',
'second': 'turtle doves',
'fifth': 'golden rings',
};
final nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};let gifts = [
"first": "partridge",
"second": "turtle doves",
"fifth": "golden rings",
]
let nobleGases = [
2: "helium",
10: "neon",
18: "argon",
]下列程式碼範例提供您可以對 Dart Map 執行的基本動作概觀。第一個範例顯示如何使用 key 算子從 Map 中擷取值
final gifts = {'first': 'partridge'};
final gift = gifts['first']; // 'partridge'使用 containsKey 方法檢查 Map 中是否已存在鍵
final gifts = {'first': 'partridge'};
assert(gifts.containsKey('fifth')); // false使用索引指派算子 ([]=) 在 Map 中新增或更新項目。如果 Map 尚未包含鍵,則會新增項目。如果鍵存在,則會更新項目的值
final gifts = {'first': 'partridge'};
gifts['second'] = 'turtle'; // Gets added
gifts['second'] = 'turtle doves'; // Gets updated若要從 Map 中移除項目,請使用 remove 方法,若要移除符合特定測試的所有項目,請使用 removeWhere 方法
final gifts = {'first': 'partridge'};
gifts.remove('first');
gifts.removeWhere((key, value) => value == 'partridge');類別
#Dart 沒有定義介面類型—任何類別都可以用作介面。如果您只想引入介面,請建立沒有具體成員的抽象類別。若要更詳細地了解這些類別,請查看 抽象類別、隱含介面 和 延伸類別 區段中的文件。
Dart 不支援值類型。如 內建類型 區段中所述,Dart 中的所有類型都是參考類型 (甚至是基本類型),表示 Dart 沒有提供 struct 關鍵字。
列舉
#列舉類型,通常稱為列舉或枚舉,是一種特殊類別,用於表示固定數量的常數值。列舉長久以來一直是 Dart 語言的一部分,但 Dart 2.17 為成員新增了增強的列舉支援。這表示您可以新增包含狀態的欄位、設定該狀態的建構函式、具有功能的方法,甚至覆寫現有成員。如需更多資訊,請查看 Dart 語言導覽中的 宣告增強的列舉。
建構函式
#Dart 的類別建構函式的工作方式類似於 Swift 中的類別初始值設定項。不過,在 Dart 中,它們提供了更多設定類別屬性的功能。
標準建構函式
#標準類別建構函式在宣告和呼叫時,看起來都非常類似 Swift 初始值設定項。Dart 使用完整類別名稱,而不是 init 關鍵字。new 關鍵字曾經是建立新類別實例的必要條件,現在則是選用的,而且不再建議使用。
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 提供了一些語法糖以簡化此作業
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);與函式類似,建構函式也可以採用選擇性位置或命名參數
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 直接設定的任何欄位之後,但在建構函式主體之前執行
class Point {
...
Point(Map<String, double> json)
: x = json['x']!,
y = json['y']! {
print('In Point.fromJson(): ($x, $y)');
}
...
}初始值設定項清單是使用斷言的好地方。
命名建構函式
#與 Swift 不同,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。
class ImmutablePoint {
final double x, y;
const ImmutablePoint(this.x, this.y);
}這也表示您可以將該類別用作常數值,使物件成為編譯時期常數
const ImmutablePoint origin = ImmutablePoint(0, 0);建構函式重新導向
#您可以從其他建構函式呼叫建構函式,例如,為了防止程式碼重複或為參數新增其他預設值
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);
}工廠建構函式
#當您不需要建立新類別實例時,可以使用工廠建構函式。一個範例是,如果可以傳回快取實例
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 中,方法都是提供物件行為的函式。
void doSomething() { // This is a function
// Implementation..
}
class Example {
void doSomething() { // This is a method
// Implementation..
}
}func doSomething() { // This is a function
// Implementation..
}
class Example {
func doSomething() { // This is a method
// Implementation..
}
}取得器和設定器
#您可以透過在欄位名稱之前加上 get 或 set 關鍵字來定義 getter 和 setter。您可能會記得每個實例欄位都有隱含的 getter,加上適當的 setter(如果適用)。在 Swift 中,語法稍有不同,因為 get 和 set 關鍵字需要在屬性陳述式內定義,而且只能定義為陳述式,不能定義為表達式
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;
}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 修飾詞。下列範例宣告一個具有抽象方法和包含預設實作方法的抽象類別
// 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 語言中,每個類別都隱含地定義一個介面,其中包含類別的所有執行個體成員和它實作的所有介面。如果您想要建立一個支援類別 B 的 API 但不繼承 B 的實作,類別 A 應該實作 B 介面。
與 Dart 不同,Swift 類別不會隱含地定義介面。介面需要明確地定義為協定,並由開發人員實作。
一個類別可以實作一個或多個介面,然後提供介面所需的 API。Dart 和 Swift 都具有不同的介面實作方式。例如
abstract class Animal {
int getLegs();
void makeNoise();
}
class Dog implements Animal {
@override
int getLegs() => 4;
@override
void makeNoise() => print('Woof woof');
}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 參照父類別
abstract class Animal {
// Define constructors, fields, methods...
}
class Dog extends Animal {
// Define constructors, fields, methods...
}class Animal {
// Define constructors, fields, methods...
}
class Dog: Animal {
// Define constructors, fields, methods...
}混合
#混入允許您的程式碼在類別之間共用功能。您可以在類別中使用混入的欄位和方法,將其功能用作類別的一部分。一個類別可以使用多個混入(當多個類別共用相同功能時很有用),而不需要彼此繼承或共用一個共同的祖先。
雖然 Swift 不支援混入,但如果您撰寫一個協定並搭配一個提供協定中指定方法的預設實作的擴充,則可以近似這個功能。此方法的主要問題是,與 Dart 不同,這些協定擴充不會維護自己的狀態。
您可以像一般類別一樣宣告混入,只要它沒有延伸 Object 以外的任何類別,而且沒有建構函式。使用 with 關鍵字將一個或多個以逗號分隔的混入新增到類別中。
下列範例顯示如何在 Dart 中達成此行為,以及如何在 Swift 中複製類似的行為
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 {
}// 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 Walker {
walk() => print('Walks legs');
}
// Impossible, as Walker is no longer a class.
class Bat extends Walker {}由於您可以使用多個混入,因此它們的方法或欄位在用於同一個類別時可能會互相重疊。它們甚至可以與使用它們的類別或該類別的父類別重疊。為了解決這個問題,Dart 會將它們堆疊在彼此之上,因此它們新增到類別中的順序很重要。
舉例來說
class Bird extends Animal with Consumer, Flyer {當在 Bird 的執行個體上呼叫方法時,Dart 會從堆疊的底部開始,從它自己的類別 Bird 開始,它優先於其他實作。如果 Bird 沒有實作,則 Dart 會繼續往上移動堆疊,接著是 Flyer,然後是 Consumer,直到找到實作。如果找不到實作,則會最後檢查父類別 Animal。
擴充方法
#與 Swift 類似,Dart 提供擴充方法,允許您將功能(特別是方法、取得器、設定器和運算子)新增到現有類型。在 Dart 和 Swift 中建立擴充的語法看起來非常類似
extension <name> on <type> {
(<member definition>)*
}extension <type> {
(<member definition>)*
}舉例來說,Dart SDK 中 String 類別上的下列擴充允許解析整數
extension NumberParsing on String {
int parseInt() {
return int.parse(this);
}
}
print('21'.parseInt() * 2); // 42extension String {
func parseInt() -> Int {
return Int(self) ?? 0
}
}
print("21".parseInt() * 2) // 42雖然 Dart 和 Swift 中的擴充功能類似,但仍有一些關鍵差異。以下各節將介紹最重要的差異,但請查看 擴充功能方法 以取得完整概觀。
命名擴充功能
#雖然不是強制性的,但您可以在 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 中,您無法使用擴充功能為類別新增其他建構函式,但您可以新增一個建立類型實例的靜態擴充功能方法。請考慮以下範例
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');覆寫成員
#覆寫實例方法(包括運算子、取得器和設定器)在兩種語言之間也非常類似。在 Dart 中,您可以使用 @override 註解表示您有意覆寫成員
class Animal {
void makeNoise => print('Noise');
}
class Dog implements Animal {
@override
void makeNoise() => print('Woof woof');
}在 Swift 中,您將 override 關鍵字新增到方法定義
class Animal {
func makeNoise() {
print("Noise")
}
}
class Dog: Animal {
override func makeNoise() {
print("Woof woof");
}
}泛型
#與 Swift 一樣,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');在此情況下,將 字串 傳遞給 轉換 方法可確保它傳回 字串。同樣地,如果提供 整數,傳回值就是 整數。
使用逗號分隔來定義多個泛型
// 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');泛型類別
#泛型也可以套用至類別。您可以在呼叫建構函式時指定類型,這讓您可以針對特定類型調整可重複使用的類別。
在以下範例中,快取 類別用於快取特定類型
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)如果省略類型宣告,執行時期類型為 快取<動態>,而且對 setByKey 的兩個呼叫都是有效的。
限制泛型
#您可以使用泛型來使用 extends 將您的程式碼限制在類型家族中。這可確保您的類別使用擴充特定類型(類似於 Swift)的泛型類型進行實例化
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 類別有一個泛型定義:類別 List<E>。泛型類型 E 指的是清單內容的類型。通常,此類型會自動推斷,並用於 List 類別的某些成員類型中。(例如,它的第一個取得器傳回 E 類型的值)。在定義 List 文字時,您可以明確定義泛型類型,如下所示
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 identicallyMap 也是如此,它也使用泛型 (class Map<K, V>)) 來定義其 key 和 value 類型
// 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 支援類似於輕量級執行緒的 Isolate,且本文不會介紹。每個 Isolate 都擁有自己的事件迴圈。如需詳細資訊,請參閱 Isolate 的運作方式。
未來
#原生 Swift 沒有與 Dart 的 Future 相應的物件。不過,如果您熟悉 Apple 的 Combine 架構,或 RxSwift 或 PromiseKit 等第三方程式庫,您可能仍然知道這個物件。
簡而言之,Future 代表非同步操作的結果,此結果會在稍後提供。如果您有一個函式傳回 String (Future<String>) 的 Future,而不仅仅是 String,您基本上會收到一個可能在稍後(未來)存在的數值。
當 Future 的非同步操作完成時,此數值就會提供。不過,您應該記住,Future 也可能以錯誤而不是數值完成。
一個範例是,如果您發出 HTTP 要求,並立即收到一個 Future 作為回應。結果出現後,Future 會以該數值完成。不過,如果 HTTP 要求失敗,例如因為網路連線中斷,Future 會以錯誤完成。
也可以手動建立 Future。建立 Future 最簡單的方式是定義並呼叫 async 函式,下一節會討論到。如果您有一個需要成為 Future 的數值,您可以使用 Future 類別輕鬆將其轉換為 Future
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,此函式的非同步對應函式會傳回 Future<String>。
在 Swift 中,async 關鍵字後面放置的 throws 關鍵字(但僅當函式可拋出時),在 Dart 的語法中不存在,因為 Dart 例外和錯誤不會由編譯器檢查。相反地,如果在非同步函式中發生例外,傳回的 Future 會因例外而失敗,然後可以適當處理。
// 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';
}然後可以如下呼叫這個非同步函式
String stringFuture = await fetchString();
print(str); // "String Value"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 中,無法從非非同步內容呼叫非同步函式。在 Dart 中,您可以這麼做,但您必須適當處理產生的 Future。不必要地從非非同步內容呼叫非同步函式被視為不良做法。
與 Swift 類似,Dart 也有 await 關鍵字。在 Swift 中,await 僅在呼叫 async 函數時才可以使用,但 Dart 的 await 可搭配 Future 類別使用。因此,await 也適用於 async 函數,因為在 Dart 中,所有 async 函數都會傳回 future。
等待 future 會暫停目前函數的執行,並將控制權傳回事件迴圈,迴圈可以在 future 以值或錯誤完成之前執行其他工作。在之後的某個時間點,await 表達式會評估為該值或擲回該錯誤。
完成後,會傳回 future 的值。您只能在 async 環境中使用 await,這與 Swift 相同。
// We can only await futures within an async context.
asyncFunction() async {
String returnedString = await fetchString();
print(returnedString); // 'String Value'
}當等待的 future 失敗時,會在含有 await 關鍵字的那一行擲回錯誤物件。您可以使用一般的 try-catch 區塊來處理這個錯誤。
// 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);
}如需更多資訊和一些實作練習,請查看 非同步程式設計 實作範例。
串流
#Dart 的非同步工具箱中的另一個工具是 Stream 類別。雖然 Swift 有自己的串流概念,但 Dart 中的串流類似於 Swift 中的 AsyncSequence。同樣地,如果您知道 Observables(在 RxSwift 中)或 Publishers(在 Apple 的 Combine 架構中),那麼 Dart 的串流應該會讓您感到熟悉。
對於不熟悉 Streams、AsyncSequence、Publishers 或 Observables 的人來說,概念如下:Stream 本質上就像 Future,但隨著時間推移,它會傳送多個值,就像事件匯流排一樣。可以監聽串流以接收值或錯誤事件,並且可以在不再傳送任何事件時關閉串流。
監聽
#若要監聽串流,您可以在 async 環境中將串流與 for-in 迴圈結合使用。for 迴圈會針對傳送的每個項目呼叫回呼方法,並在串流完成或發生錯誤時結束。
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;
}如果在監聽串流時發生錯誤,錯誤會在包含 await 關鍵字的那一行擲回,您可以使用 try-catch 陳述式來處理這個錯誤。
try {
await for (final value in stream) { ... }
} catch (err) {
print('Stream encountered an error! $err');
}這並非監聽串流的唯一方法:您也可以呼叫其 listen 方法並提供一個回呼,這個回呼會在串流傳送值時呼叫。
Stream<int> stream = ...
stream.listen((int value) {
print('A value has been emitted: $value');
});listen 方法有一些用於錯誤處理或串流完成時的選用回呼。
stream.listen(
(int value) { ... },
onError: (err) {
print('Stream encountered an error! $err');
},
onDone: () {
print('Stream completed!');
},
);listen 方法會傳回 StreamSubscription 的執行個體,您可以使用它來停止監聽串流。
StreamSubscription subscription = stream.listen(...);
subscription.cancel();建立串流
#與 future 一樣,您有許多不同的方法可以建立串流。最常見的兩種方法是使用非同步產生器或 SteamController。
非同步產生器
#非同步產生器函數的語法與同步產生器函數相同,但使用 async* 關鍵字而非 sync*,並傳回 Stream 而不是 Iterable。這種方法類似於 Swift 中的 AsyncStream 結構。
在非同步產生器函式中,yield 關鍵字會將給定的值傳送至串流。不過,yield* 關鍵字會與串流搭配使用,而不是其他可迭代物件。這允許從其他串流傳送事件至這個串流。在下列範例中,函式只會在最新傳送的串流完成後才會繼續執行
Stream<int> asynchronousNaturalsTo(int n) async* {
int k = 0;
while (k < n) yield k++;
}
Stream<int> stream = asynchronousNaturalsTo(5);您也可以使用 StreamController API 建立串流。如需更多資訊,請參閱 使用 StreamController。
文件註解
#一般註解在 Dart 中與 Swift 中的運作方式相同。使用雙斜線 (//) 會註解出雙斜線後方該行的所有內容,而 /* ... */ 則會區塊註解出跨越多行的內容。
除了一般註解之外,Dart 也有 文件註解,可與 dart doc 搭配使用:這是第一方工具,可為 Dart 套件產生 HTML 文件。建議在所有公開成員的宣告上方放置文件註解。您可能會注意到,這個程序類似於您在 Swift 中為各種文件產生工具新增註解的方式。
與 Swift 相同,您可以使用三個正斜線 (///) 而不是兩個 (//) 來定義文件註解
/// The number of characters in this chunk when unsplit.
int get length => ...在文件註解中,使用方括弧將類型、參數和方法名稱括起來。
/// Returns the [int] multiplication result of [a] * [b].
multiply(int a, int b) => a * b;雖然支援 JavaDoc 樣式的文件註解,但您應該避免使用,並使用 /// 語法。
/**
* The number of characters in this chunk when unsplit.
* (AVOID USING THIS SYNTAX, USE /// INSTEAD.)
*/
int get length => ...函式庫和可見性
#Dart 的可見性語意與 Swift 相似,Dart 函式庫大致等同於 Swift 模組。
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 個模組。
屬於函式庫的所有檔案都可以存取該函式庫中的所有私有物件。但基於安全性考量,檔案仍需要允許特定檔案存取其私有物件,否則任何檔案(即使來自專案外部)都可以註冊到你的函式庫,並存取可能具敏感性的資料。換句話說,私有物件不會在函式庫之間共用。
library animals;
part 'parrot.dart';
class _Animal {
final String _name;
_Animal(this._name);
}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 之間的主要差異。在這個階段,你可以考慮移至 Dart 或 Flutter(一個使用 Dart 建立美觀、原生編譯、多平台應用程式的開放原始碼架構,從單一程式碼庫進行開發)的一般文件,在那裡你可以找到有關語言和入門實務的深入資訊。