Dart 抱怨的代碼:
Map<String,int> get_frequency(String text) {
Map<String,int> retval = {};
for (int i = 0; i<text.length; i) {
retval[text[i]] = retval[text[i]] ?? 0;
retval[text[i]] ; //<---- this is where dart is complaining.*
}
return retval;
}
void main() {
const paragraphOfText = 'Once upon a time there was a Dart programmer who '
'had a challenging challenge to solve. Though the challenge was great, '
'a solution did come. The end.';
var data = get_frequency(paragraphOfText);
print(data);
}
顯然用 (*) 標記的行不能為空,那么我如何告訴 Dart 呢?我嘗試了空斷言運算子 (!),但是沒有用。
空安全已啟用。
錯誤資訊:
challenge2.dart:5:20: Error: Operator ' ' cannot be called on 'int?' because it is potentially null.
retval[text[i]] ;
^
challenge2.dart:5:20: Error: A value of type 'num' can't be assigned to a variable of type 'int'.
retval[text[i]] ;
^
uj5u.com熱心網友回復:
一個可能的解決方案是改變線路
retval[text[i]] ; //<---- this is where dart is complaining.*
進入
retval[text[i]] = retval[text[i]]! 1;
剛剛想通了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/344864.html
標籤:镖
