dart - 价值知识!= null
问题描述
如果我在代码中这样写,编译器知道什么value
不是空的
// IT WORKS GOOD
int? value = getIntOrNull();
if (value != null) {
// now compiler know what value is not null
int strongInt = value;
} else {
AssertionError('value should be not null');
}
但我怎么能像guard
in那样做呢swift
?我尝试通过 来执行此操作assert
,但在这种情况下,编译器不知道什么value
不为空。
// IT DOESN'T WORK
int? value = getIntOrNull();
assert(
value != null,
'value should be not null',
);
// now compiler does not know what value is not null
// how I can do the same behaviour like in `if`
int strongInt = value; // error: request `value!`
解决方案
断言不会在生产模式下执行,因此之后的代码assert
不受断言测试的保护。int strongInt = value;
有可能(通过value
不null
执行断言)来解决这个问题,因此程序不是sound。仅当所有使用路径都通过确保提升类型的测试时,编译器才会提升。
所以,一个assert(test)
不会比
if (assertsEnabled && !(test)) throw AssertionError();
whereassertsEnabled
在编译时是未知的。
推荐阅读
- oauth-2.0 - 启动 light-oauth2 图像时,它显示 service.yml 中没有可用的路由处理程序提供程序
- javascript - 当我使用 npm 安装某些东西时出现问题
- c - Do-While 循环正在工作但没有得到最终输出
- list - 点击 Tab bar 过滤列表 Flutter
- sql - Nodejs Mysql Insert 正在向字符串添加反斜杠并失败
- r - 从我的随机森林模型中获得仅 NA 响应的问题
- java - GSON解析器在循环json时跳过对象
- android - 如何减少 Android 中的 Reactive Native 应用程序内存使用量
- websocket - 随机额外的 websocket 连接到凤凰应用程序?
- angular - 从订阅者 Angular 获取数据的问题