Dart 語言系列
Built-in types ( 內(nèi)置類型)
Dart
語言特別支持以下類型:
numbers
strings
booleans
lists (also arrays)
maps
runes (for expressing Unicode characters in a string)
symbols
你可以初始化任何一種類型的對象使用字符独旷。例如: 'this is a string'
是一個字符串字符狗超,true
是一個 boolean
字符菇用。
因為在Dart
語言中,每一個變量都引用這一個對象 - 是類的實例 - 通常你可以使用構(gòu)造函數(shù)初始化變量额获,一些內(nèi)置的類型是它們自己的構(gòu)造函數(shù)呐芥。例如润脸,你可以使用Map()
構(gòu)造函數(shù)創(chuàng)建一個Map
.
Numbers
Dart
中 numbers
有兩種類型:
int
整數(shù)值不超過64bit ,取決于平臺嚼酝。在Dart
虛擬機中 ,值可以從 -2^63
到 2^63 - 1
. 被編譯成JavaScript
的 Dart
使用 JavaScript numbers,竟坛,值的范圍在 -2^53
to 2^53 - 1
.
double
64位(雙精度)浮點數(shù)闽巩,按照IEEE 754
的標準。(注:最廣泛使用的浮點數(shù)運算標準)担汤。
int
和 double
都是 num
的子類型涎跨。num
類型包括基本的操作符,例如 +
-
*
/
,并且包括 abs()
ceil()
floor()
及其他方法(按位操作符崭歧,例如 >>
,被定義在 int
類中.)如果num
和他的子類型你沒有找到的話隅很,在[dart:math(https://api.dartlang.org/stable/dart-math)
這個庫中可能存在。
整數(shù)是不包含小數(shù)點的率碾。這里定義整數(shù)字符的例子:
var x = 1;
var hex = 0xDEADBEEF;
如果includes
包含小數(shù)叔营,它就是double
,這里有定義double
類型字符的例子:
var y = 1.1;
var exponents = 1.42e5;
在 Dart 2.1
中,整數(shù)字符自動的被轉(zhuǎn)換為 doubles
如果需要的話:
double z = 1; // Equivalent to double z = 1.0.
版本注意點:在Dart 2.1
之前所宰,在double
中使用了整數(shù)字符是錯誤的绒尊。
這里是如何將字符串轉(zhuǎn)換為number
,或者反過來也是一樣的:
// String -> int
var one = int.parse('1');
assert(one == 1);
// String -> double
var onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);
// int -> String
String oneAsString = 1.toString();
assert(oneAsString == '1');
// double -> String
String piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == '3.14');
int
類型指定了傳統(tǒng)的位移運算(<<
>>
) AND (&)
OR(|)
等操作符。例如:
assert((3 << 1) == 6); // 0011 << 1 == 0110
assert((3 >> 1) == 1); // 0011 >> 1 == 0001
assert((3 | 4) == 7); // 0011 | 0100 == 0111
Literal numbers
是編譯期常量歧匈,很多數(shù)學表達式也是編譯期常量垒酬,只要它們的操作數(shù)是計算數(shù)字的編譯時常量。
const msPerSecond = 1000;
const secondsUntilRetry = 5;
const msUntilRetry = secondsUntilRetry * msPerSecond;
Strings
一個 Dart
字符串是一系列 UTF-16
編碼的單元件炉。你可以使用單引用(''
) 或者雙引用(""
) 來創(chuàng)建一個字符串:
var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to use the other delimiter.";
你可以使用${expression}
在字符串內(nèi)給一個表達式賦值勘究。如果表達式是一個標識,你可以跳過 { }
.為了得到一個對象對應(yīng)的字符串斟冕。Dart
中可以調(diào)用對象的toString()
方法.
var s = 'string interpolation';
assert('Dart has $s, which is very handy.' ==
'Dart has string interpolation, ' +
'which is very handy.');
assert('That deserves all caps. ' +
'${s.toUpperCase()} is very handy!' ==
'That deserves all caps. ' +
'STRING INTERPOLATION is very handy!');
Note: ++
操作符來判斷兩個對象是否相等口糕,如果兩個字符串包含兩個相同序列的編碼單元它們是相等的.
你可以使用相鄰字符串來拼接字符串或者使用+
操作符。
var s1 = 'String '
'concatenation'
" works even over line breaks.";
assert(s1 ==
'String concatenation works even over '
'line breaks.');
var s2 = 'The + operator ' + 'works, as well.';
assert(s2 == 'The + operator works, as well.');
另一種創(chuàng)建多行字符串的方法是:使用三個成對的單引號(''' '''
) 或者三個成對的雙引號(""" """
):
var s1 = '''
You can create
multi-line strings like this one.
''';
var s2 = """This is also a
multi-line string.""";
你可使用r
來創(chuàng)建一個raw
(保持字符串原始字符) 的字符串:
var s = r'In a raw string, not even \n gets special treatment.';
可以參考 Runes 來了解更多字符串中表達 Unicode
字符磕蛇。
字符串是編譯期常量景描,任何內(nèi)插表達式都是編譯時常量,等同于null
numeric
string
或者 boolean
值秀撇。
// These work in a const string.
const aConstNum = 0;
const aConstBool = true;
const aConstString = 'a constant string';
// These do NOT work in a const string.
var aNum = 0;
var aBool = true;
var aString = 'a string';
const aConstList = [1, 2, 3];
const validConstString = '$aConstNum $aConstBool $aConstString';
// const invalidConstString = '$aNum $aBool $aString $aConstList';
更多關(guān)于字符串的使用超棺,可以參考 Strings and regular expressions。
Booleans
為了表示boolean
類型的值呵燕,Dart
有一種定義類型 bool
.只有兩個對象具有bool類型,他們boolean
表示是 true
和 false
,他們都是編譯期常量.
Dart
是類型安全的標明你不需要使用代碼棠绘,如 if (nonbooleanValue)
或者 assert (nonbooleanValue)
.相反的,你可以準確的進行值檢查,例如:
// Check for an empty string.
var fullName = '';
assert(fullName.isEmpty);
// Check for zero.
var hitPoints = 0;
assert(hitPoints <= 0);
// Check for null.
var unicorn;
assert(unicorn == null);
// Check for NaN.
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);
Lists
通常氧苍,最通用的集合對每一個編程語言來說可能是array
,或者有序的對象組夜矗。在Dart
中,arrays
是 List
對象,因此大多數(shù)人將它們稱為lists
.
Dart
的list
字面表達類似于 JavaScript
。 這里有一個Dart list
的例子:
var list = [1, 2, 3];
**Note: 編譯器會推斷出list
的類型是List<itn>
.如果你嘗試添加一盒非整數(shù)類型的對象到這個列表中让虐,編譯器或者運行期就會報錯紊撕。更多的信息可以參考 type inference
**.
為了創(chuàng)建一個運行時常量,可以在list
前添加一個 const
:
var constantList = const [1, 2, 3];
// constantList[1] = 1; // Uncommenting this causes an error.
List
類型有很多遍歷的方法來操作列表赡突。更多lists
的信息对扶,可以參照 Generics 和 Collections.
Maps
通常,一個map
是一個對象惭缰,關(guān)聯(lián)著keys
和 values
.keys和
values 可以使任何類型的對象辩稽。每一個
key 只能出現(xiàn)一次,但是你可以有多個相同的值从媚。
Dart對
maps的支持是由
map literals和
Map` 提供的。
這里有兩個簡單的Dart maps
的例子患整,使用map
創(chuàng)建:
var gifts = {
// Key: Value
'first': 'partridge',
'second': 'turtledoves',
'fifth': 'golden rings'
};
var nobleGases = {
2: 'helium',
10: 'neon',
18: 'argon',
};
Note:編譯器是推斷出 gifts
的類型是 Map<String, String>
和 nobleGases
的類型是 Map<int, String>
,如果你嘗試添加一個錯誤類型的值到map
,編譯器或者運行時會報錯拜效,更多信息,你可以參考 type inference.
你也可以創(chuàng)建相同的對象各谚,使用Map
的構(gòu)造函數(shù):
var gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';
var nobleGases = Map();
nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';
Note:你可能期望看到 new Map()
而不是 Map()
.由于在Dart 2
中 new
這個關(guān)鍵字是可選的紧憾。更多細節(jié),可以參照 Using constructors.
新增一個 key-value pair
到已存在的map
中和JavaScript
一樣:
var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds'; // Add a key-value pair
取出一個值從 map
中和你在 JavaScript
中是一樣的:
var gifts = {'first': 'partridge'};
assert(gifts['first'] == 'partridge');
如果你在Map
中查找一個不存的key
,你將會得到返回值為null
:
var gifts = {'first': 'partridge'};
assert(gifts['fifth'] == null);
使用 .length
可以得到 key-value pairs
的數(shù)量在 map
中:
var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds';
assert(gifts.length == 2);
創(chuàng)建一個編譯期常量的map
,在map
前添加 const
:
final constantMap = const {
2: 'helium',
10: 'neon',
18: 'argon',
};
// constantMap[2] = 'Helium'; // Uncommenting this causes an error.
更多關(guān)于Maps
的信息昌渤,可以參照 Generics
和 Maps赴穗。
Runes
Dart
中,runes
是 字符串的 UTF 32
的代碼點膀息。
Unicode
為世界上所有書寫系統(tǒng)中使用的每個字母般眉,數(shù)字和符號定義唯一的數(shù)值。因為Dart
是一系列的 UTF-16
的代碼單元潜支,如果在一個字符串中要表達32位 Unicode
的值需要特定的語法.
通常表達一個Unicode
的點是 \uXXXX,
XXXX 是4個數(shù)字十六進制的值甸赃。例如:??這個字符 是 \u2665
。若要指定多于或少于4個十六進制數(shù)字冗酿,請將值置于花括號中埠对。例如 ,??的表情是 \u{1f600}
.
String
這個類有幾個屬性可以提取 rune
的信息。codeUnitAt
和 codeUnit
屬性將返回16位的代碼單元裁替。使用 runes
屬性可以得到一個字符串的runes
.
以下例子證明了runes
16-bit code units
32-bit code points
之間的關(guān)系.
var clapping = '\u{1f44f}';
print(clapping);
print(clapping.codeUnits);
print(clapping.runes.toList());
Runes input = new Runes(
'\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}');
print(new String.fromCharCodes(input));
Note:當使用list
操作符操作runes
時要當心项玛。這種方法容易中斷,依賴于特殊的語言弱判,字符集合和操作符襟沮。更多的信息,可以參照 How do I reverse a String in Dart? 在 Stack Overflow
上
Symbols
在Dart
程序中 ,一個 Symbols
對象代表一個操作符或者一個標識臣嚣。你可能從來也不會使用symbols
,但它們對于通過名稱引用標識符的API
非常有用净刮,因為縮小會更改標識符名稱而不會更改標識符符號。
要獲取標識符的符號硅则,請使用符號文字淹父, #
后面跟著標識符:
#radix
#bar
Symbol
字符是編譯期常量。